why use malloc with structure?

2020-06-17 01:57发布

问题:

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

#include <stdio.h>
#include <conio.h>

struct node {
    int data;
    struct node *l;
    struct node *r;
};

int main(){
    //Case 1
    struct node n1;
    n1.data = 99;
    printf("n1 data is %d\n", n1.data);

    //Case 2
    struct node *n2 = (struct node *) malloc (sizeof(struct node));
    n2 -> data = 4444;
    printf("n2 data is:%d\n",n2 -> data);
    free(n2);

    return (0);
}
  1. I am having hard time to understand how n1 which is not initialized to memory location is able to store data (99) .
  2. when to use case 1 and when to use case 2.

回答1:

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

You use malloc, to allocate memory on heap, and without malloc, you are placing you struct in stack memory.

I am having hard time to understand how n1 which is not initialized to memory location is able to store data (99) .

Initialized or not, when you assign data n1.data = 99; , it is stored.

2) when to use case 1 and when to use case 2

Case 1 is is used, when you know that you will be using the structure object within a confined scope, and will not be making references to the structure data, beyond its scope.

Case 2 is used when you will be using your structure at multiple places, and you are willing to manage memory for it manually(and carefully!). The advantage of this method is that, you create and initialize the structure at some part of the program scope, and you create a pointer and pass the pointer around, since passing a 4 byte pointer is far more efficient than , passing the structure itself.



回答2:

int main() {
    struct node n1;
    n1.data = 99

This reserves space on the stack (in main's frame) equivalent to the size of a struct node. This is known as a local, and it only exists within the context of main.

struct node *n2 = (struct node *) malloc (sizeof(struct node));

This is an allocation on the heap. This memory exists no matter what function context you are in. This is typically called "dynamic allocation".

These node structures are the basis for a linked list, which can have nodes added, removed, re-ordered, etc. at will.

See also:

  • What and where are the stack and heap?


回答3:

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.



回答4:

Normally you use malloc only, if you don't know the size of memory you will need before the application is running.

Your code is correct, but you can't allocate memory dynamically. What if you want to save a measured value in the node.date and you don't know, how many measures you will capture? Then you have to malloc some new memory on each measure you take.

If you define all the nodes before run-time (directly in the code), you can't save more measures than you've defined before.

Search for linked lists in c and you will find some good examples.



回答5:

Your data type looks like a node in a tree. Two primary reasons to use malloc for tree node allocations would be

  1. To allocate the arbitrary number of nodes. The number of tree nodes will in general case be a run-time value. For this reason, it is impossible to declare the proper number of local variables for such nodes since all local variables have to be declared at compile time. Meanwhile, malloc can be called in run-time as many times as you want, allocating as many node object as you need.

  2. To make sure that the node does not be destroyed automatically when the lifetime of the local object ends (i.e. at the end of the block). Objects allocated by malloc live forever, i.e. until you destroy them explicitly by calling free. Such object will transcend the block boundaries and function boundaries. Nothing like that is possible with local objects, since local objects are automatically destroyed at the end of their block.

Your code sample does not depend on any of the benefits of dynamic allocation, since it doe snot really create a real tree. It just declared as single node. But if you attempt to build a full tree with run-time number of nodes, yo will immediately realize that it is impossible to do by declaring nodes as local objects. You will unavoidably have to allocate your nodes using malloc.

Your "how n1 which is not initialized to memory location is able to store data" question must be caused by some confusion. struct node n1; is an object definition, which means that it assigns a memory location for n1. That's exactly the purpose of object definition.



标签: c structure