char *p; placement and mysterious segfault on sprintf(p, "%d", 3);

Tom Browder TBrowder@cox.net
Mon May 19 10:33:00 GMT 2003


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




More information about the Gcc-help mailing list