Is there a way that you can assign memory from heap without a call to malloc? Can the following call be affective for it?
void* loc = (void*) &heap[end_of_heap];
Is there a way that you can assign memory from heap without a call to malloc? Can the following call be affective for it?
void* loc = (void*) &heap[end_of_heap];
No. The C language itself provides no such functionality. If you only care about Unix systems conforming to a deprecated feature of an old version of the Unix standard (SUSv2 or earlier, if I remember correctly), the brk
and sbrk
functions provide this functionality. But you really should not use it unless you're writing very low-level code that will never need to be portable.
There is no way to get a pointer to new and valid heap memory other than using a heap allocating function. You cannot simply add a pointer into the heap at the end of an existing pointer and expect to reliably access it.
There is no portable way besides malloc and friends, but if you're willing to get platform-specific sbrk (and brk
) in old-fashioned Unix (not in current Posix), used to be the underlying syscalls. Now their manpage says
Avoid using brk() and sbrk(): the malloc(3) memory allocation package is the portable and comfortable way of allocating memory.
and that advice is surely good (no real advantage in using the old-fashioned syscalls even in platforms that supply them). mmap
of some /dev/
is a totally different way for some modern Unix versions, Windows has its own totally different "win32 API calls" for the purpose, and so on.
The Standard does not say anything about heap (search it, if you don't believe this). An implementation is not even required to have a heap (as we commonly know it).
However, the short answer to your question is, no in Standard C. Unless of course you use a platform specific API. Typically, OS APIs sometimes do give you some leeway as to accessing memory.
You cannot access heap reliably without malloc, but there are alternatives for memory allocation.
If you're trying to get finer control over memory allocations, you can use other memory managers like bget memory allocator. Here you grab a huge chunk of heap (the maximum memory requiredment anticipated + some overhead) using malloc
and pass it to the bget using bpool
. From there on, call bget
instead of malloc
to allocate memory and brel
to free it. bget is reportedly better in avoiding memory fragmentation.