restrict dodginess

P

Phil Carmody

if printf takes a restrict pointer, then what happens in
printf("%s", "%s");
Is the compiler obliged to have 2 copies of the string?

Phil
 
B

Ben Bacarisse

Phil Carmody said:
if printf takes a restrict pointer, then what happens in
printf("%s", "%s");
Is the compiler obliged to have 2 copies of the string?

I don't think so. The limitations imposed by restrict only apply when
one or more of the objects pointed to are modified, and since that
would be undefined anyway I don't think compiler needs to care.

Even if it were not UB to modify the content of a string literal, I
don't think the implementation is obliged to correct the programmer.
For example, in a hypothetical C where such modifications are
permitted

sscanf("%c", "%c", "%c");

can be undefined (due to the restrict qualifiers and aliased pointers)
because you wrote a bad call.
 
S

Seebs

if printf takes a restrict pointer, then what happens in
printf("%s", "%s");
Is the compiler obliged to have 2 copies of the string?

I think the conclusion that was reached eventually was that this was
technically undefined behavior, because the compiler is perfectly allowed
to do something which, in this case, invokes undefined behavior. This
doesn't seem to matter much.

There was some discussion about something closely related to this in
some case involving arguments to sprintf where you could conceivably want
this, and the sense of the committee, if I recall correctly, was that
it's rare enough that people can do the extra work.

The reason printf's format string has to be restrict is this:

union {
char s[4];
int x;
} foo;
strcpy(foo.s, "%n");
printf(foo.s, &foo.x);

You can easily expand this, using longer and more interesting format strings,
into a form where there's a real possibility of something going wrong.

-s
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,085
Messages
2,570,597
Members
47,220
Latest member
AugustinaJ

Latest Threads

Top