Andy Andy - 5 months ago 35
C Question

Cannot change character in char array

According to this question: When should I use malloc in C and when don't I?

Using malloc to allocate memory should allow me to change one of the characters in the array. However, this program crashes at run time. Can someone please advise? (also

causes a different crash which is why it is commented out).

char* ptr;
ptr = (char *)malloc(sizeof(char[10]));
ptr = "hello";
ptr[0] = 'H';
printf("The string contains: %s\n", ptr);
//free (ptr);
return 0;


Your program crashes because this line

ptr = "hello";

completely undoes the effect of malloc from the previous line:

ptr = malloc(sizeof(char[10])); // No need to cast to char*

and it also creates a memory leak along the way, because the address returned by malloc is irrecoverably lost after the assignment.

Once the assignment is done, an attempt to set ptr[0] = 'H' results in a crash, because you are trying to modify the memory of the string literal itself - i.e. undefined behavior.

In C strings need to be copied, not assigned if you want to modify them later. Replace the assignment with strcpy call to fix this problem.

strcpy(ptr, "hello");