سؤال

In c,the code like this :

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    int item;
    struct node* next;
}Node;

    Node * newNode(int i)
    {
        Node *x=malloc(sizeof(Node));
        x->item=i;x->next=NULL;
        return x;
    }
    int main()
    {
        int a=2;
        Node *p=newNode(a);
        printf("%d\n",p->item);
        return 0;
    }

after the function newNode(int) is over,pointer x was released,then pointer p get a junk address.But the result is 2.Please explain this process.thanks.

هل كانت مفيدة؟

المحلول

After the function newNode() pointer x was NOT released, because you never used free(x), hence the pointer is still valid!

return x;

The value of x here is the address of the memory location where the Node struct exists.

Node *p=newNode(a);

Here the variable p of type pointer (meaning, it's value is an address) will be equal to the value returned by newNode(), so it will be pointing to the same item that x was pointing to inside the newNode() function.

نصائح أخرى

If I understand your question, you think that since x is released (by exiting the function), p should be junk. This is incorrect. first the address pointed to by x is placed on the return stack. Then x is released, because you have left the function and x is now out of scope. The return logic places the value from the return stack into p. The address obtained by the malloc was not freed and is pointed to by p.

C does not release memory until explicitly told to do so. Even if it would automatically release the memory when all references go away, the reference is still kept through the return into p.

Consider a simple arithmetic opertion

int func(a, b)
  {
    int c = a+b;
    return(c);
   }

int d = 0;
d = func(1, 2);
printf('%d\n', d);

The output is 3 even though c became junk, because the value was passed through. Similarly, the address was passed through and the contents of that memory location are still valid because you did not call free() on the allocated memory area.

Your condition is.valid for build in data types.. but for malloc we use free to release the memory. So the value perists even after the call to function is over.and the value exists in main program because it uses address rather than value.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top