I think all malloc(sizeof(structure))
can be replaced this way:
char[sizeof(structure)]
Then when is malloc
necessary?
I think all malloc(sizeof(structure))
can be replaced this way:
char[sizeof(structure)]
Then when is malloc
necessary?
When you don't know how much memory to allocate at compile time. Take a very simple program, where you need to store the numbers entered by the user in linked list. Here you dont know how many numbers will be entered by the user. So as user enters a number you will create a node for it using
malloc
and store it in the linked list.You should read about dynamic memory allocation. You obviously don't know what it is.
The main difference between the two is that memory allocated with
malloc()
exists until you say so. Static memory such aschar buff[10];
only exists in the function scope.Besides the fact that your
char[]
method cannot resize or determine the size at runtime, your array might not be properly aligned for the type of structure you want to use it for. This can result in undefined behaviour.You never should do this the way you are proposing. Others already told you about the difference of allocating storage on the heap versus allocation on the function stack. But if and when you are allocating on the stack you should just declare your variable:
There is no sense or point in doing that as an (basically) untyped
char
array. If you also need the address of that beast, well, take the address of with&A
.You will use malloc to dynamically allocate memory, either because:
I can see your point. You could think you could always using a declarative syntax for all of these, even using variables to declare the size of your memory spaces, but that would:
You will probably get to understand this in time, don't worry.
Also, you should try to learn more about the memory model. You don't use the same memory spaces when using a dynamic allocation and when using a static allocation.
For first pointers, visit:
Friendly advice: I don't know if you develop C on *NIX or Windows, but in any case if you use gcc, I recommend using the following compilation flags when you teach yourself:
malloc is a dynamic memory allocator which helps u up to assign memory to ur variables according to ur need and therefore reduces the loss of memory.It is also supported by realloc() function through which u can edit the memory required which u have defined earlier through malloc() or calloc(). So in short we can say that malloc() can be used for managing the memory space and making use of the necessary memory without wasting it.