1

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!

  • what is length of string `Hello World`? It's more then you actually allocate and you have to copy string using `strcpy`. – Jayesh Bhoi Sep 14 '14 at 08:45

3 Answers3

4

str = "Hello World"; makes str point to a constant char string "Hello World", and the memory you have malloced will become memory leak.

noark
  • 336
  • 3
  • 6
1

You copy a string with strcpy from <string.h>, not by re-assigning a pointer.

But take care that the target buffer will actually hold strlen(source) + 1 characters (0-terminator). "Hello World" is 11+1.

Also, trying to modify that improperly assigned string literal is UB.

Anyway, Don't cast the result of malloc (and friends).

Finally, return EXIT_SUCCESS is superfluous (since C99 main has an implicit return 0; at the end).

Community
  • 1
  • 1
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
0

You are throwing away the return value of malloc. Instead you are setting it to a value in read only memory

Try replacing

str = "Hello World";

with

strcpy(str, "Hello World");

You will need to include the appropriate header file

Ed Heal
  • 59,252
  • 17
  • 87
  • 127