If you don't already know, I'm learning C and memory allocation and management techniques. I've downloaded the Linux kernel source code and I'm currently inspecting conventions and techniques used by the Linux kernel developers.
As you would expect, I've been looking into the memory allocation/management header( mempool.h ). I've noticed that they've used a void* when declaring a memory handle. So, I tried to use a void* in a test memory allocation program and it simply won't let me access the data within the memory pool.
Here is my code that I already have( everything ):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <stdlib.h>
int main( )
{
void *Mem_handle = NULL;
if( ( Mem_handle = ( int * )calloc( 2, sizeof( int ) ) ) == NULL )
{
// Undecided control...
return 1;
}
Mem_handle[ 0 ] = 0; // Error occurs here. Se below for the error.
free( Mem_handle );
Mem_handle = NULL;
return 0;
}
Error( s ):'void*' is not a pointer-to-object type.
How can I access the data within the memory pool?
It's obvious that the Linux kernel developers know how to do this. So, instead of searching through multiple thousand lines of code, I thought I'll turn to you guys.
You don't need any rocket science here. You can't derefer a void* because void is is the "not-really-a-type" - type. I don't really know what you are trying to do there, but to actually access memory pointed to by a void* you have to cast it to a pointer type you can derefer.
PS: Usually, you'd have some sort of algorithm to create a memory pool of a specific size, and when the user requests memory from the pool you return a pointer to a block of unused memory inside of that pool. When people request memory, they normally have a pointer at the other end ex:
Uh, as I said... I don't really know why exactly you want to derefer your void* 's anyways. You should have some sort of function to return a void* to memory inside of your pool, and the user decides what he wants to do with that memory.
if( ( Mem_handle = ( int * )calloc( 2, sizeof( int ) ) ) == NULL )
Basically, you are reserving enough memory for 2 ints here. What you are going to do with that isn't really an issue of the memory pool, but of what you need the memory for.