char *p; placement and mysterious segfault on sprintf(p, "%d", 3);
Dave King
dking04@comcast.net
Mon May 19 17:53:00 GMT 2003
Tom,
If I read your response correctly, solution to this problem is to allocated
enough space for the buffer p? Is this a bug in gcc or just not setting up
sprintf correctly? I have run into this same problem and it has been driving
nuts.
Thanks
Dave King
dking04@comcast.net
----- Original Message -----
From: "Tom Browder" <TBrowder@cox.net>
To: "Miernik" <miernik@ctnet.pl>; <gcc-help@gcc.gnu.org>
Sent: Monday, May 19, 2003 6:33 AM
Subject: 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
>
>
More information about the Gcc-help
mailing list