Frage zu UB bei Mischung von C und C++

OP (Firma: RUB) #6101401
Lesenswert?

Hallo Forum,

folgendes Gedankenspiel:

Ich habe in einer Datei A C++-Code und in einer Datei B habe ich C-Code. 
Der C-Code enthaelt Code, der in C i.O. ist, aber in C++ UB ausloesen 
wuerde (z.B. typepunning mit unions).

Datei A wird als C++, Datei B als C compiliert. Wenn ich das jetzt 
zusammenlinke, habe ich dann UB oder nicht? Ist es fuer diese Frage 
wichtig, ob der C-Code aus C++, oder C++-Code aus C heraus aufgerufen 
wird?

Gruesse
Gast #6101707
Lesenswert?

DPA schrieb:
> Gibt's das überhaupt?

Natürlich.
Vermutlich würde er sonst auch nicht fragen.

DPA schrieb:
>> (z.B. typepunning mit unions).
>
> Das ist doch auch in C UB, oder?

https://en.wikipedia.org/wiki/Type_punning#Use_of_union

> Accessing [one member] after initializing the other member [...], is
> still a form of type-punning[2] in C and the result is unspecified
> behavior[3] (and undefined behavior in C++ [4]).
>
> ---
>
> 2. "§ 6.5.2.3/3, footnote 97", ISO/IEC 9899:2018 (PDF), 2018, p. 59, "If
> the member used to read the contents of a union object is not the same as
> the member last used to store a value in the object, the appropriate part
> of the object representation of the value is reinterpreted as an object
> representation in the new type as described in 6.2.6 (a process sometimes
> called “type punning”). This might be a trap representation."
> 
https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf
> 3.  "§ J.1/1, bullet 11", ISO/IEC 9899:2018 (PDF), 2018, p. 403, "The
> following are unspecified: … The values of bytes that correspond to union
> members other than the one last stored into (6.2.6.1)."
> 
https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf
> 4. ISO/IEC 14882:2011 Section 9.5

Unspecified vs. undefined!

> 3.28 Undefined behavior: behavior for which this International Standard
> imposes no requirements
> 3.29 Unspecified behavior: behavior, for a well-formed program construct
> and correct data, that depends on the implementation
> 3.12 Implementation-defined behavior: behavior, for a well-formed program
> construct and correct data, that depends on the implementation and that
> each implementation documents

Antwort schreiben

Bitte melde dich an, um einen Beitrag zu schreiben.

oder

Mit Google-Account einloggen

Die Registrierung ist kostenlos und dauert nur eine Minute.

Jetzt registrieren