Subject: Re: snprintf() problem or I am stupid C programmer
To: Manuel Bouyer <bouyer@antioche.lip6.fr>
From: Jon Lindgren <jlindgren@slk.com>
List: current-users
Date: 07/17/2001 15:51:22
On Tue, 17 Jul 2001, Manuel Bouyer wrote:
> On Tue, Jul 17, 2001 at 11:51:52AM -0400, Ciarcinski, Adam (ISS Brussels) wrote:
> > Hello,
> >
> > First of all, sorry for putting it on this list, but I'm using NetBSD.
> > I have problem with the following, simple, piece of C code:
> >
> >
> > #include <stdio.h>
> >
> > int main()
> > {
> > char *test = "Test";
> >
> > printf("%s\n", test);
> > snprintf(test, 5, "Passed");
> > printf("%s\n", test);
> >
> > return 0;
> > }
> >
> >
> > If you compile and run it - crash!
> > If you change 'char *test' to 'char test[]' - works!
> >
> > Tried with egcs-1.1.2 and gcc-2.95.3 on NetBSD-current (yesterday sources).
>
> gcc will allocate strings in text segment, which means they're read-only.
> I'm not sure what changing * to [] - either move the string from text to
> data segment, or copy it to stack and have test point to it instead of
> the address in text.
http://www.eskimo.com/~scs/C-faq/q1.32.html
Basically, *test allocates a constant in the text segment. test[] creates
an array, and initializes it.
-
Jon
--------------------------------------------------------------------
'"The chicken," it's been said, "is just an egg's way of making more
eggs."' -- Alton Brown