-1

I put this code on my C compiler (Dev Cpp).

char *str = "SomeTHing";
for(int i = 0; str[i]; i++){
   str[i] = tolower(str[i]);
}

This gives a segmentation fault whereas if i use a static array,

char str[10] = "SomeTHing";

the loop works fine. Can anyone tell why is this happening?

alk
  • 69,737
  • 10
  • 105
  • 255

2 Answers2

5

char *str = "SomeTHing"; allocates read-only memory to the pointer str. To change its contents in any way is undefined behaviour. On your system that is manifesting itself as a crash. It's a pity that (i) your compiler is not warning you about your assigning this to a char* rather than a const char* or (ii) you're ignoring the warning.

char str[10] = "SomeTHing"; allocates the buffer on the stack, including the null terminator. Changing its contents is defined, although you need to keep a null terminator intact if you want to use some of the string library functions like strlen that rely on it.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
4
char *str = "SomeTHing";

will place SomeTHing in the read-only parts of the memory and making str a pointer to that, making any writing operation on this memory illegal. Any try to modification this cause Undefined Behaviour.

Now following case

char str[10] = "SomeTHing";

this is working because puts the literal string in read-only memory and copies the string to newly allocated memory on the stack. it will probably be stored within an "initialized data segment" that is loaded from the executable file into write able memory when the program is run.

Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73