[Solved] why using sizeof in malloc?


sizeof doesn’t return the size of the memory block that was allocated (C does NOT have a standard way to get that information); it returns the size of the operand based on the operand’s type. Since your pointer is of type struct A*, the sizeof operand is of type struct A, so sizeof always returns 8.

So, even if you allocate 1 byte for a 10000 byte structure, you will still see sizeof return 10000.

If you don’t allocate enough memory for that object (e.g. because sizeof(int) < sizeof(struct A)) but you try to use the object anyway, you’ll encounter undefined behaviour – your program is no longer well defined and anything could happen (nothing, crashing, memory corruption, hackers owning your computer).

1

solved why using sizeof in malloc?