why use malloc with structure?

前端 未结 5 1628
没有蜡笔的小新
没有蜡笔的小新 2021-02-14 22:33

Why would I use malloc when same job can be done by without malloc as below..

#include 
#include 

struct node {
    int data;
             


        
5条回答
  •  生来不讨喜
    2021-02-14 22:45

    In the first case, memory is allocated on the stack. When the variable n1 runs out of scope, the memory is released.

    In the second case, memory is allocated on the heap. You have to explicitly release memory resources (as you are doing with free).

    Rule-of-thumb can be that you use stack-allocated memory for local, temporary data structures of limited size (the stack is only a portion of the computer's memory, differs per platform). Use the heap for data structures you want to persist or are large.

    Googling for stack and heap will give you much more information.

提交回复
热议问题