-1

My code does not crash when I write:

char s[44] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
memmove(s, "asdf", 5);

But it does when I write:

char* s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
memmove(s, "asdf", 5);

Does anyone know why?

speller
  • 1,641
  • 2
  • 20
  • 27
  • did you get segmentation fault? are you compiling with gcc? – Anantha Krishnan Mar 16 '12 at 10:26
  • Refer this http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c – Anantha Krishnan Mar 16 '12 at 10:32
  • 3
    Trying to modify a string literal is Undefined Behaviour. In your case, apparently, the UB makes your program crash; in another computer it might change the contents of the string literal; in yet another computer it might make lemon juice ooze out of the USB port. – pmg Mar 16 '12 at 11:13

3 Answers3

7

first one allocates space and puts the a's in

second one is a pointer to constant memory, you aren't allowed to change it.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
1

In the first case, 44 bytes are allocated on stack and the string "aa..a" is copied to this space. But in the second space, the string "aa..a" is a constant value and stored in the read only data segment. So a page fault will occur when you try to write a read only memory address.

Jinghao Shi
  • 1,077
  • 2
  • 10
  • 15
1

char* s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

the string constant "aaaa" whatever is stored in a the memory which is readonly. For example in elf executables they will be stored in the .rodata section, which is nor writable. Therefore when you attempt to write at such a location it results in an errorhe

On the other hand char s[] will have the string stored in the local stack area, which you can modify.

phoxis
  • 60,131
  • 14
  • 81
  • 117