a question about structure convert to char* in function printf/fprintf

2018-08-12 Thread zerons

Hi all,

As we know, gcc would give us an error message when we do this:
`struct _test a; char *s = a;`;

However, when we use this in printf/fprintf, it gets wired.
```c
#include 

struct _test {
char name[256];
};
struct _test tests[100];

int main(int argc, char *argv[])
{
memcpy(tests[0].name, "hello0", 6);
memcpy(tests[1].name, "hello1", 6);
memcpy(tests[2].name, "hello2", 6);

for (int i = 0; i < 3; i++) {
#if 1
/* output hello1 */
printf("%s\n", tests[i]);
/* output looks to be all right */
printf("%d %s\n", i, tests[i]);
printf("%d %d %s\n", i, i, tests[i]);
#else
printf("%s\n", tests[i], "hello gcc");
#endif
}

return 0;
}
```
Gcc just give a warning message, and copy the structure to stack,
some registers will be reset(%rsi...), then ignore the argument `tests[i]`,
which means `#else` will output `hello gcc`.

Should gcc give it an error to prevent a structure from converting to
char* in functions printf/fprintf?

Best regards,


Re: a question about structure convert to char* in function printf/fprintf

2018-08-12 Thread zerons




On 08/13/2018 03:13 AM, Jonathan Wakely wrote:

On Sun, 12 Aug 2018 at 15:59, zerons wrote:

Should gcc give it an error to prevent a structure from converting to
char* in functions printf/fprintf?


Your question is inappropriate on this mailing list, please use
gcc-help next time. See https://gcc.gnu.org/lists.html

I'm so sorry for that.



Did you try compiling with warnings? If not, why not.

-Werror=format will give you an error.


Oh, I forget to use -Werror. I use -Wall a lot. :(
Unfortunately I didn't try to solve all the warnings.
Thanks.