0

C Memory Allocation

================================ #include <stdio.h> #include <stdlib.h> int main() { int *ptr; printf("Size of ptr %d\n", sizeof(ptr)); ptr = (int *)malloc(sizeof(int) * 10); printf("Size of ptr %d\n", sizeof(ptr)); return (0); } ================================ In the above code, I expected the size of ptr must have been changed from 4 to 40... Anybody who can tell me where I went wrong...

22nd Mar 2021, 9:07 AM
Arun Bhattacharya
Arun Bhattacharya - avatar
4 odpowiedzi
+ 7
sizeof(ptr) will return the amount of memory that pointer is taking in the memory (which is 4 bytes) and not the memory it is pointing to.
22nd Mar 2021, 9:21 AM
Arsenic
Arsenic - avatar
+ 2
Arsenic thanks, is there any way to see how much memory is allocated after the allocation
22nd Mar 2021, 9:23 AM
Arun Bhattacharya
Arun Bhattacharya - avatar
+ 2
Arun Bhattacharya there is no standard way to find the memory allocated by malloc() in C. You have to either keep track of it on your own. P.S. Some implementations also comes with functions to do this stuff for you, like _msize in MSVC.
22nd Mar 2021, 9:30 AM
Arsenic
Arsenic - avatar
+ 2
Arsenic Thanks a lot buddy...
22nd Mar 2021, 10:20 AM
Arun Bhattacharya
Arun Bhattacharya - avatar