Not understanding what happens in memory during dynamic memory allocation using pointers in C?


#include<stdio.h>

#include<stdlib.h>

int main()

{

    int *p;

    p=(int *) malloc(4);

    if(p==NULL)

    {

        printf("Insufficient memory");

        return;

 

    }

    printf("Enter a number\n");

    scanf("%d",p);

 

    printf("Value of p=%d",*p);

 

}

 

1) What happens in background when we do int *p? Can you show a figure about what it does in memory?

 

2) What happens in memory "p=(int *) malloc(4);" when we run this line? In surface, I've rote memorized, it allocates 4 bytes of memory, but I don't know in detail what happens in background.

 

3) printf("Enter a number\n");

    scanf("%d",p);

 

I need to store a number in address of p, so should not I do &p instead of just p?

 

4) Value of p=p isn't it? Why *p? I've again rote memorized *p gives value of p, but I'm not clear about what's going inside memory during this all.

 

I'm asking these questions knowing I'm wrong because I've tested the code in codeblocks already. It's not to get the correct answer but a way to think to get a correct answer.

 

If we'd done;

int x=10;

int *p=&x;

I'd understand what's being done here.

It means content of p is initialzed with address of x. Like this:

https://imgur.com/a/7BNzsGO

but I don't understand the above case that I mentioned in question where we are only doing int *p. I find it meaningless. p is a pointer variable. But it contains whose address?


Asked by:- shivajikobardan
0
: 884 At:- 3/25/2023 5:43:07 AM
c c++ pointers







1 Answers
profileImage Answered by:- neena

What happens in background when we do int *p? 

-> Memory is allocated

 What happens in memory "p=(int *) malloc(4);" when we run this line? In surface, I've Wrote memorized, it allocates 4 bytes of memory, but I don't know in detail what happens in background.

->  you are correct here, I am not sure what else you need to know here.

I need to store a number in address of p, so should not I do &p instead of just p?

-> yes

 Value of p=p isn't it? Why *p? I've again rote memorized *p gives value of p, but I'm not clear about what's going inside memory during this all.

-> when you call *p, it will refer address where value is stored, so it returns value.

 

0
At:- 3/25/2023 4:32:50 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use