658 views
0 votes
0 votes

how to know how much size is allocated while dynamically allocating memory to the pointer variable with malloc.

i just write the below code to know the size of ptr2 after dynamically allocating memory.

i want the output is 10 but it is displaying as 2 as( 8 / 4 )

#include<stdio.h>
#include<stdlib.h>
int main()
{
	int *ptr2,i;
	ptr2=(int*)malloc(10*sizeof(int));//how much size is allocated????
	if(ptr2==NULL)
		printf("memory allocation failed");
	else{
			printf("size of *ptr2  is == %d\n",(sizeof(ptr2)/sizeof(int)));
	}
}

 

1 Answer

0 votes
0 votes

In this program, memory allocated $10\times 4=40B$, Here, ptr2 just pointing first element of that memory i.e. $4B$

But, integer pointer holds size of $8$ byte. U can run this and understand

#include<stdio.h>
#include<stdlib.h>
int main()
{
	int *ptr2,i;
	ptr2=(int*)malloc(10*sizeof(int));//how much size is allocated????
	if(ptr2==NULL)
		printf("memory allocation failed");
	else{
			printf("size of *ptr2  is == %d\n",(sizeof(ptr2)));
	}
}

So, when u want to print dividing ptr2 size with integer size, it will printing $\frac{8}{4}=2$

Ref:https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/

https://stackoverflow.com/questions/2259890/using-sizeof-on-mallocd-memory

edited by

Related questions

1 votes
1 votes
1 answer
2
Mrityudoot asked Feb 2
249 views
In what cases does an uninitialized array have values = 0 and for which cases does it have values = garbage values. How to differentiate?
0 votes
0 votes
0 answers
3
Ahsanul Hoque asked Mar 16, 2018
290 views
queue->array = (int*) malloc(queue->capacity *sizeof(int));What is queue->capacity * doing here?