Why can't I use this code to overwrite a string?

后端 未结 4 901
刺人心
刺人心 2020-12-11 11:50

Code:

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

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

O

4条回答
  •  抹茶落季
    2020-12-11 11:56

    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";
    

提交回复
热议问题