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

William C. Cox bcox@windriver.com
Wed Apr 25 07:34:00 GMT 2001


Hi Markus,

Compile the program to assembly code with '-S'.  I'll 
bet that you find that gcc has put the string literal
into a read-only data section, and your workstation
has used a read-only memory page for that section.
Attempting to store into the constant therefore causes
the seg fault.  In the second case, the compiler allocates
space in main()'s stack frame, copies the literal into
it, and doesn't fail because the stack frame *must* be
writable.

Try it out!

>>>>>
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?

------- 8< ----------------------
#include <stdio.h>

/* Taken from K&R 2nd ed. p 47 */

void squeeze(char *s, char c)

{

    int i=0, j=0;


    for (i=0,j=0; s[i] != '\0'; i++) 

        if (s[i] != c) 

            s[j++] = s[i];

    }

    s[j] = '\0'; 

}

int main(void)

{

    char *test = "4444 2222 7777 8888";


    squeeze(test, ' ');


    printf("New string: %s\n", test);


    return 0;

}






More information about the Gcc-bugs mailing list