This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: char *p; placement and mysterious segfault on sprintf(p, "%d", 3);
The fundamental problem is you haven't allocated space for the buffer p for
sprintf to operate on.
In the example:
> make_message(const char *fmt, ...) {
> /* Guess we need no more than 100 bytes. */
> int n, size = 100;
> char *p;
> va_list ap;
notice p was allocated 100 bytes:
> if ((p = malloc (size)) == NULL)
> return NULL;
> while (1) {
> /* Try to print in the allocated space. */
> va_start(ap, fmt);
> n = vsnprintf (p, size, fmt, ap);
>
I can't explain exactly why you didn't get a seg fault in the various
combinations, but you were just the temporarily lucky recipient of undefined
bevhavior which didn't crash in those conditions.
And I believe you WOULD have gotten a crash in all the cases if you had
tried to print 'p', e.g., if you had added a line such as:
printf("%s\n", p);
Tom