If you don't know the exact size of the memory you need to use, you need dynamic allocation (malloc
). An example might be when a user opens a file in your application. You will need to read the file's contents into memory, but of course you don't know the file's size in advance, since the user selects the file on the spot, at runtime. So basically you need malloc
when you don't know the size of the data you're working with in advance. At least that's one of the main reasons for using malloc
. In your example with a simple string that you already know the size of at compile time (plus you don't want to modify it), it doesn't make much sense to dynamically allocate that.
Slightly off-topic, but... you have to be very careful not to create memory leaks when using malloc
. Consider this code:
int do_something() {
uint8_t* someMemory = (uint8_t*)malloc(1024);
// Do some stuff
if ( /* some error occured */ ) return -1;
// Do some other stuff
free(someMemory);
return result;
}
Do you see what's wrong with this code? There's a conditional return statement between malloc
and free
. It might seem okay at first, but think about it. If there's an error, you're going to return without freeing the memory you allocated. This is a common source of memory leaks.
Of course this is a very simple example, and it's very easy to see the mistake here, but imagine hundreds of lines of code littered with pointers, malloc
s, free
s, and all kinds of error handling. Things can get really messy really fast. This is one of the reasons I much prefer modern C++ over C in applicable cases, but that's a whole nother topic.
So whenever you use malloc
, always make sure your memory is as likely to be free
d as possible.
malloc()
can fail! – Heterotypic