String constants vs char arrays in C [duplicate]

夙愿已清 提交于 2019-12-04 17:12:55
servn

At least on my computer, the following program crashes:

#include <stdio.h>
int main() { 
  char *p = "this is a string constant";
  *(p+2) = 'a';
  printf("%s", p);
}

If it appears to be working for you (which it might on certain embedded compilers), you're just getting lucky. Undefined behavior means the program is allowed to do anything. See http://blog.regehr.org/archives/213 .

See also What is the difference between char s[] and char *s?.

In case of char array the content of the string literal "blah" are copied on to the stack as well. So you can modify it without invoking UB because after all its just a copy.

In case of char * you actually try to modify the original string literal and as per the Standard that is UB.

With a string constant, there's not guarantee about where the data will be stored -- the compiler is free to do any tricks it wants, because you're supposed to be forbidden from writing to it. So for example, it's not unheard of for the pointer to actually point to the spot in the loaded executable code itself where the string constant is defined.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!