String/Array Question

M

Matthew Alton

Why does this code generate a SIGSEGV?

#include <stdio.h>

int
main(void)
{
char *s = "ABC";

s[1] = 'X';

return(0);
}

while this does not:

#include <stdio.h>

int
main(void)
{
char s[] = "ABC";

s[1] = 'X';

return(0);
}


The *s declaration followed by a reference to s[-1] is used in
FreeBSD's strsep(3). It dumps core on Red Hat Linux 7.x and NetBSD
1.6.1.
 
B

Barry Schwarz

Why does this code generate a SIGSEGV?

#include <stdio.h>

int
main(void)
{
char *s = "ABC";

s[1] = 'X';

return(0);
}

while this does not:

#include <stdio.h>

int
main(void)
{
char s[] = "ABC";

s[1] = 'X';

return(0);
}

Because your compiler is doing it best to comply with the requirement
that a string literal be non-modifiable. See the faq at
http://www.eskimo.com/~scs/C-faq/top.html. The answer to your
question is near the beginning but you should read the whole thing.


<<Remove the del for email>>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top