+ 1

Having troubles with malloc() and sizeof()

As seen in the code, why does sizeof(ab2) always return 8? Even if I allocated it any integer it always returns 8. I'm new to low level stuff so please forgive me https://code.sololearn.com/cTorJUrz51od/?ref=app

30th Apr 2021, 4:52 AM
かんでん
かんでん - avatar
4 odpowiedzi
+ 2
かんでん malloc() allocates some memory on the heap for your program to acess ( accessing a memory block which is not allocated to your program would lead to undefined behaviour ). Once the memory is allocated, malloc() returns a pointer pointing to that memory block to your program. Using sizeof() on a pointer object would return the size of a pointer itself and not the address it is holding in it. This is similar to how using sizeof() on an integer variable would return the size of int datatype and not the value in it.
30th Apr 2021, 5:52 AM
Arsenic
Arsenic - avatar
+ 1
Hey かんでん , 1.size of pointers is 8 bytes (64-bit machine) because pointers are storing a memory address and not the values of variable ! 2.The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of void which can be casted into pointers of any form. Syntax: ptr = (castType*) malloc(size); I suggest you to study through websites or youtube channel , because these topics are little bit harder for beginners!
30th Apr 2021, 4:56 AM
Giriraj Yalpalwar
Giriraj Yalpalwar - avatar
0
Thirt13n I'm still a bit confused. What does malloc() do then? I'm trying to access the allocated bytes for ab2 How do I access it? Thank you very much
30th Apr 2021, 4:57 AM
かんでん
かんでん - avatar