tags:

views:

91

answers:

4

Code:

#include "stdio.h"
#include "string.h"

int main()
{
  char *p = "abc";
  printf("p is %s \n", p);
  return 0;
}

Output:

p is abc

Code:

#include "stdio.h"
#include "string.h"

int main()
{
  char *p = "abc";
  strcpy(p, "def");
  printf("p is %s \n",p);
  return 0;
}

Output:

Segmentation fault (core dumped)

Could someone explain why this happens?

A: 

Because p is pointing to read only memory.

Overwriting data that p points to results in undefined behavior. A string literal is any string you specify explicitly in quotes. All string literals are read only. (Note: You can use a string literal to initialize a char array.)

You need to instead allocate your own buffer like this:

char buffer[4];
strcpy(buffer, "def");
printf("buffer is %s \n", buffer);
Brian R. Bondy
+5  A: 

In your code:

char *p="abc";

p points to a string literal - you are not allowed to change string literals, which is what your call to strcpy is trying to do. Instead, make p an array:

char p[] = "abc";

which will copy the literal into something that you are allowed to modify.

anon
you are not allowed to change string literals - WHY ?
aks
@aks Because the C Standard says so. The thinking is that the compiler may place them in read-only memory. However, the standard does not require that a compile diagnose problems like yours - it says what you get is "undefined behaviour", in your case a seg fault.
anon
+2  A: 

Because p points to a read-only memory region (__TEXT segment) which contains the string "abc".

As you strcpy it, a read-only memory region is going to be overwritten, which is illegal. So the kernel will SegFault your program.

If you want writable memory, you need to allocate it on the stack

char p[1024] = "abc";

or on the heap

char* p = malloc(1024);
...
free(p);

or in the __DATA segment (i.e. a global variable)

static char p[1024] = "abc";
KennyTM
Doesn't have to be the TEXT section. Many place it in separate read-only sections (rdata, rodata, etc). Just a sidenote since the main point is, as you pointed out, read-only'iness.
joveha
@joveha: Since I don't know the ELF format I just consider the case in Mach-O :). In Mach-O these stuff are placed in the __TEXT,__const section I think.
KennyTM
A: 

p is basically just a pointer to read-only data (which is "abc" in your case). You cannot overwrite that with "def".

Ree