Does this means using one of (malloc or calloc or realloc) and one of(brk/sbrk) concurrently results in UB or using both malloc and calloc can also cause UB?
This happends through the entire program or just a source file?
Does this means using one of (malloc or calloc or realloc) and one of(brk/sbrk) concurrently results in UB or using both malloc and calloc can also cause UB?
This happends through the entire program or just a source file?
Copyright © 2021 Jogjafile Inc.
The actual rule, on systems that have both
sbrkandmalloc, is "The implementation ofmallocmay assume that no code other than itself callssbrkwith a nonzero argument."Phrased this way, the consequences are much easier to deduce:
There must be only one operational implementation of
mallocper process. (On systems like this, the OS-provided C library'smallocis usually designed to notice and gracefully step aside when you supply another implementation.)It is fine to call
sbrk(0)anywhere you want.If you are writing an implementation of
malloc, you may go right ahead and callsbrkwith a nonzero argument, and assume that nobody else will.But if you are not writing an implementation of
malloc, callingsbrkwith a nonzero argument will probably cause the next call tomalloc(or any function that callsmallocinternally, which could be any of them except those documented as async-signal-safe) to crash the process or corrupt the heap.It should be easy to see why calling
sbrkwith a negative argument, from outside themallocimplementation, can have this effect. You shrank the heap! There might have been allocations in the space that you took away! There almost certainly are internalmallocbookkeeping structures in there!Why calling
sbrkwith a positive argument can have the same effect is more subtle.mallocwon't know about the additional space. The next timemalloccallssbrkitself, it will update its internal bookkeeping structures incorrectly. There will be a chunk of memory in the middle of the heap that it's not able to track. It's very likely to scribble on that memory and/or confuse itself into accessing addresses outside the heap.