If you do not know the exact size of the used memory, you need dynamic allocation ( malloc ). For example, a user may open a file in your application. You will need to read the contents of the file in memory, but, of course, you do not know the file size in advance, since the user selects the file in place at run time. So basically you need malloc when you don’t know in advance the size of the data you are working with. At least one of the main reasons for using malloc . In your example with a simple line that you already know, size at compile time (plus you don't want to change it), it doesn't make much sense to dynamically highlight this.
A little 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);
You see what is wrong with this code? There is a conditional return expression between malloc and free . It may sound good at first, but think about it. If there is an error, you will return without freeing the allocated memory. This is a common source of memory leaks.
Of course, this is a very simple example, and it is very easy to see an error 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 dirty very quickly. This is one of the reasons why I prefer modern C ++ over C when applicable, but this is a whole topic.
Therefore, whenever you use malloc , always make sure your memory is as free as possible.
adam10603 Apr 24 '16 at 12:19 2016-04-24 12:19
source share