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

后端 未结 4 902
刺人心
刺人心 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:57

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

提交回复
热议问题