Modifying a string defined in a header file

May 4, 2012 at 4:37pm
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?
May 4, 2012 at 4:45pm
char *hello = "hello, world";
This is no longer allowed because the string literal gives you a const array. It has to be
const char *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
1
2
3
const char* str = "hello, world";
char* hello = new char[std::strlen(str) + 1];
std::strcpy(hello, str);

3. use std::string (this is probably the easiest way). std::string hello = "hello, world";
Last edited on May 4, 2012 at 4:46pm
May 4, 2012 at 4:52pm
Thanks for the explanation.
Topic archived. No new replies allowed.