This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: What is the difference between char *str and char str[] ?


On Wed, Apr 25, 2001 at 04:04:13PM +0200, Markus Virtanen wrote:
> 
> I have a small test program that causes seg fault if 
> I define a string as: char *test = "some text";
> and pass that string to a function that manipulates it. 
> However if I define it as char test[] = "some string"; 
> everything works fine.
> 
> Again some detail I didn't learn at University?

Hi Markus

test[] = "some string" 
initializes the the array test with 12 Bytes (the string and a trailing 0)
on the stack.

char *test = "some text";
puts the string "some text" (and the trailing 0) into the nonwritable section
and sets the pointer test to its beginning. It allocates only sizeof(char*) on
the stack.
You should have got a warning from gcc, but i do not get one, either
(gcc -Wall -O).

Microsoft's compiler gives an incompatible pointer assignment warning IIRC
(pointer to const char cannot be assigned to pointer to char).

Try: gcc -fwritable-strings.

Hope that helps,
Martin.

-- 
The early bird gets the worm. If you want something else for       
breakfast, get up later.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]