views:

361

answers:

4

I'm specifically focused on when to use malloc on char pointers

char *ptr;
ptr = "something";
...code...
...code...
ptr = "something else";

Would a malloc be in order for something as trivial as this? If yes, why? If not, then when is it necessary for char pointers?

+4  A: 

malloc is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:

char *literal = "foo";

However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc:

char *buf = malloc(BUFSIZE); /* define BUFSIZE before */
// ...
free(buf);
dirkgently
+2  A: 

Use malloc() when you don't know the amount of memory needed during compile time. In case if you have read-only strings then you can use const char* str = "something"; . Note that the string is most probably be stored in a read-only memory location and you'll not be able to modify it. On the other hand if you know the string during compiler time then you can do something like: char str[10]; strcpy(str, "Something"); Here the memory is allocated from stack and you will be able to modify the str. Third case is allocating using malloc. Lets say you don'r know the length of the string during compile time. Then you can do char* str = malloc(requiredMem); strcpy(str, "Something"); free(str);

Naveen
+2  A: 
scotchi
What would be wrong with: char *foo = "bar";char *bar = foo; printf("%s\n", bar);
ZPS
First, it should be `const char *foo...`, second, in your example that just copies the pointer, not the data. `strdup()` actually copies the data as well.
scotchi
+1  A: 

Everytime the size of the string is undetermined at compile time you have to allocate memory with malloc (or some equiviallent method). In your case you know the size of your strings at compile time (sizeof("something") and sizeof("something else")).

Lucas