char[] or *char malloc?

Asked

Viewed 2,384 times

14

What difference in C between

char text[10]

or

char *char = (char *)malloc(10*sizeof(char)); 

What advantage of using malloc on a pointer?

  • 2

    Not the need to type cast malloc, see here.

2 answers

16

The first allocates 10 locations in memory (probably in the stack, but it depends on the context where it’s being used) for a type char that in the case has guaranteed size of 1 byte. And this storage location will be called text.

The second allocates memory in the heap also for 10 positions of type char (sizeof(char) is unnecessary). The function malloc() return a pointer to the location of the allocated memory and this pointer can be stored in the variable (in this case it was called char, but that name is invalid).

The use of malloc() which is stored in the heap allows the object to survive even after the function (or stack frame) end. If it were allocated to stack, he is destroyed at the end of stack frame where it was allocated. It may also be a problem for the stack if the size to allocate is large or not easily determined as small.

If you don’t have one free() somewhere there will probably be a memory leak.

In C++ it is not recommended to use either.

Further reading:

14


The main advantage is that you don’t need to know the size (in your case, 10) a priori. If you know exactly how much space you need when creating your program, and you will only use that memory address within the function where the variable is declared (see next paragraph), then using the first syntax is more convenient (since you don’t have to worry about releasing the allocated memory).

Like malloc allocates space in heap instead of on the stack, the allocated value can be valid even after the function where it is started ends - on the stack when the function (scope) ends, the stack space is released; on the heap you are responsible for releasing the memory.

  • In this case char text[10] will be allocated in the stack by the compiler?

  • 1

    Yeah, or at least you can assume so. It is possible that the compiler has some optimization in the code that it is allocated elsewhere, but this optimization cannot go against the premises that the data is allocated in the stack.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.