What difference in C between
char text[10]
or
char *char = (char *)malloc(10*sizeof(char));
What advantage of using malloc on a pointer?
What difference in C between
char text[10]
or
char *char = (char *)malloc(10*sizeof(char));
What advantage of using malloc on a pointer?
The main advantage is that you do not need to know the size (in your case, 10) a priori. If you know exactly how much space you need when you are creating your program, and you will only use that memory address within the function where the variable is declared (see the next paragraph), then using the first syntax is more convenient (since you do not have to worry about releasing the crazy memory.)
As malloc
allocates space in heap rather than in stack, the allocated value may be valid even after the function where it is started ends - in stack when function ) ends, stack space is released; in heap you are responsible for releasing memory.
The first one allocates 10 positions in memory (probably in the stack , but depends on the context where it is being used) for a type char
which in this case has a guaranteed size of 1 byte. The storage location will be called text
.
The second allocates memory in heap also for 10 positions of type char
( sizeof(char)
is unnecessary). The malloc()
function will return a pointer to the allocated memory location and this pointer can be stored in the variable (in this case it was called char
, but this name is invalid).
Using malloc()
allows the decision to be made dynamically. As it is stored in the heap the object survives even after the function (or stack frame ) ends. If it is allocated in stack , it is destroyed at the end of the stack frame where it was allocated. It can also be a problem for the stack if the size to allocate is large or not easily determined as small.
In C ++ it is not recommended to use either.
Further Reading: