I\'m trying to learn more about memory allocation, and so I wrote some test code below to see what would happen if I tried to allocate memory of a less size than what I need
In this specific case, you are potentially trying to allocate 0 bytes, because sizeof(Object)
is 8 in most 32-bit compilers. malloc(0)
will return NULL
as its an invalid size to be allocated, and trying to write to address NULL
will certainly crash your application.
But lets suppose you successfully allocate 4 bytes, and try to write 8 bytes within it. In a single thread application it should probably work without issues, because despite you will be writing to unallocated memory space, it will not be exactly writing to some crazy address lost in the virtual memory.
Howover, if you do this:
Object* a = (Object*)malloc(4);
Object* b = (Object*)malloc(4);
It is potentially true that a
and b
were allocated in serie. It means that, in most 32-bit compilers, writing to a->number
will overwrite b->message
with the same value and vice versa, because both will be trying to store information to the same space in memory.
To answer the subquestion about sizeof: sizeof yields a result based on the type that you are using (in C, there is a separate case for variable length arrays). If you write
T* obj = malloc (any value);
then sizeof (*obj) just looks at the type of *obj, which is T, and yields the size of an object of type T. It doesn't matter whether the allocation failed and obj is actually NULL, or whether you allocated fewer or more bytes than the size of a T, it doesn't even matter if you didn't call malloc at all and obj is an uninitialised variable.
it depends on the compiler and the os. On many, it eventually crashes. Definitely not recommended. Can potentially lead to buffer overflow as well.
It is good that you are doing this kind of exploration. Most standard c libraries include non standard extensions that allow you to check the size of memory after it is allocated. You should call that after returning from malloc and see how much memory the standard library is actually allocating if you want to learn more about how malloc
is implemented. You may find that something as simple as malloc(1)
can return a sizeable memory chunk.
As some other readers pointed out, you may be askking malloc
to allocate zero bytes in your example code if you were to recompile on a 32 bit system. It will happily comply and return NULL
.