c – malloc(): memory corruption

c – malloc(): memory corruption

It is undefined behavior because you have allocated 8192 bytes memory but you are trying to write 9200 bytes. Which is out of bound.

What may cause this difference?

Basically, the memory allocator allocates pages of memory at once for use by programs, and it gives you a pointer within them (making sure the following space is free for use). Since these pages are usually bigger than 8KiB, you have no issue in your mini-program. But if a larger program is allocating larger amounts of memory and writing further and further past the end of your allocated space, then youll end up attempting to write into unallocated memory (or memory used by another program!), thus corrupting memory.

c – malloc(): memory corruption

Writing to memory which you have not allocated is undefined behaviour. Thats because malloc() returns a section of memory which you may write to, so when you write past the end of that region, you are overwriting something which is not yours.

That could be a structure used by malloc itself, or something else entirely.

Leave a Reply

Your email address will not be published.