Hey guys, I am trying to modify a C string that has been defined in a header file, however I have been running into segmentation faults. I wrote up some very simple example code that demonstrates what I am trying to do.
In the file test.h:
char *hello = "hello, world";
In the file test.c:
1 2 3 4 5 6 7 8
#include "test.h"
int main ()
{
printf("%s\n", hello);
hello[0] = 'o';
printf("%s\n", hello);
return 0;
}
Result:
1 2
hello, world
Segmentation Fault (core dumped)
Does anyone know if this is possible? Is there some kind of work around for this type of thing?
char *hello = "hello, world";
This is no longer allowed because the string literal gives you a const array. It has to be constchar *hello = "hello, world";
Now you will notice why it doesn't work. It's because you can't modify const data.
If you want to modify the string content you can do one of the following.
1. store the string in a static array char hello[] = "hello, world";
2. dynamically allocate the string array