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?
As was indicated by others, you don't need to use malloc just to do:
The reason for that is exactly that
*foo
is a pointer — when you initializefoo
you're not creating a copy of the string, just a pointer to where"bar"
lives in the data section of your executable. You can copy that pointer as often as you'd like, but remember, they're always pointing back to the same single instance of that string.So when should you use malloc? Normally you use
strdup()
to copy a string, which handles the malloc in the background. e.g.Now, we finally get around to a case where you may want to malloc if you're using
sprintf()
or, more safelysnprintf()
which creates / formats a new string.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 useconst 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 dochar* str = malloc(requiredMem); strcpy(str, "Something"); free(str);
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: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
:malloc for single chars or integers and calloc for dynamic arrays. ie
pointer = ((int *)malloc(sizeof(int)) == NULL)
, you can do arithmetic within the brackets ofmalloc
but you shouldnt because you should usecalloc
which has the definition ofvoid calloc(count, size)
which means how many items you want to store ie count and size of data ieint
,char
etc.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")).