2

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 free(ptr) 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;
Community
  • 1
  • 1
Andy
  • 275
  • 2
  • 14

2 Answers2

4

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");
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

There are several things that need to be fixed:

char* ptr = 0;
ptr = (char *)malloc(sizeof(char)*10);
if(!ptr)
    return 0; // or something to indicate "memory allocation error"
strcpy(ptr, "hello");
ptr[0] = 'H';
printf("The string contains: %s\n", ptr);
free (ptr);
return 0;

This compiles and runs correctly in main()

Rob11311
  • 1,396
  • 8
  • 10
alain
  • 11,939
  • 2
  • 31
  • 51
  • you should explain why instead of just posting code – user1231232141214124 Jun 08 '14 at 21:19
  • yes, but I saw dasblinkenlight's answer after I had written mine, so I felt there was no need to improve my answer anymore. I could have deleted it, but I left it because of the `malloc` return value check. – alain Jun 08 '14 at 21:31