Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value in pointer string array in C

Is it possible to change a value in a character array initialized by a string pointer this way:

char *word;
word = (char*) malloc(10 * sizeof(char));
word = "Test";
word[2] = 'w';

return 0;

I get a segmentation fault while executing the above code.


1 Answers

You get a crash because you do this:

word = "Test";
word[2] = 'w';

The first assignment changes the pointer, so it no longer points to the memory you have allocated but to a string literal. And string literals are actually read-only character arrays. And as they are read-only, your attempt of modifying the array in the second assignment will lead to undefined behavior.

The correct way is to copy the string to the memory you have allocated, which you do with the strcpy function:

strcpy(word, "test");

Another thing with the reassigning of the pointer is that you then loose the pointer to the allocated memory, and have a memory leak. You can not call free on the pointer either, since the memory pointed to by word (after your original reassignment) is no longer allocated by you, which would have caused another case of undefined behavior.

like image 108
Some programmer dude Avatar answered Aug 31 '26 13:08

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!