I am attempting to change a character in a character array.
In the code below, there are three attempts to do this. Only the first one will succeed. The last two both segfaults. If I understand correctly, str_one is declared in the heap, and could therefore be manipulated; and in contrast, str_two is declared in the stack and is therefore immutable, thus the segfault, when update it is attempted. However, I understand that using malloc, one is able to assign a pointer and allocate space in heap memory. Thus, I should be able to manipulate the assigned variable str_three. Doing so, however, results in a segfault.
I hope someone can shed light on this. Thanks!
Code:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char const* argv[])
{
char str_one[4092] = "This is string number one";
char * str_two = "This is string number two";
char * str_three;
str_three = (char *) malloc(4092);
str_three = "This is the third string";
str_one[5] = 'X';
printf("%s\n", str_one);
str_two++;
*str_two = 'X'; // segfaults here
str_two--;
printf("%s\n", str_two);
str_three++;
*str_three = 'X'; // segfaults here
str_three--;
printf("%s\n", str_three);
return 0;
}