I'm trying to figure out how to use malloc correctly in C, and have run into an error that I'm having trouble with.
My code:
#include <stdio.h>
#include <stdlib.h>
int main() {
char * str;
str = (char *)malloc(10);
str = "Hello World";
str[0] = 'R';
return EXIT_SUCCESS;
}
My Valgrind output:
==23136== Process terminating with default action of signal 10 (SIGBUS)
==23136== Non-existent physical address at address 0x100000F92
==23136== at 0x100000F66: main (test.c:12)
I know that the issue is due to me trying to allocate the letter 'R' to str
, but I was under the impression that the advantage of using malloc
in this situation (as opposed to char str[10] = "Hello World"
), was the ability to edit the contents of my string.
Thanks!