-1

If I want to change the pointed value without changing the pointer's address, what should I do?

In 3, *d=*b will return segmentation fault in running time. I think it is because the *d is not pointed to any memory space. This also explains why 2, works. However, for 1, *a and *b pointed to memory with same size, why it will return segmentation fault here?

void main(void){
    char *a="abcd";
    char *b="1234";
    char *c=(char *)malloc(sizeof(char));
    char *d;
    *a=*b; //1.segmentation fault
    *c=*b; //2.ok
    *d=*b; //3.segmentation fault
}
Mykola
  • 3,343
  • 6
  • 23
  • 39
Edw
  • 15
  • 6
  • 3
    You cannot change string literals. Any attempt at modifying them gives undefined behavior. This code cannot work. – Cody Gray - on strike Feb 13 '16 at 13:37
  • 2
    Possible duplicate of [Why do I get a segmentation fault when writing to a string initialized with "char \*s" but not "char s\[\]"?](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha), http://stackoverflow.com/questions/10202013/change-string-literal-in-c-through-pointer, http://stackoverflow.com/questions/1011455/is-it-possible-to-modify-a-string-of-char-in-c/1011481, http://stackoverflow.com/questions/480555/modifying-c-string-constants – Cody Gray - on strike Feb 13 '16 at 13:39

2 Answers2

2

Constant strings are usually stored in read only memory and you can't modify them.

To make them writable create a copy first:

char *a = strdup("abcd");
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
1

This is because strings, such as "abcd" are constant in C. It is undefined behaviour to try to modify one.

If you want the string to be modifiable, you have to declare it like this:

char a[] = "abcd";

This will declare a local array and initialise it with the content of the string (which is different from declaring a pointer which points to the string)

Elias Mårtenson
  • 3,820
  • 23
  • 32