I have an assignment in which I have to create a function to allocate a block with a starting index multiple of an int called "alignment" and a given size.
function prototype is
int block_alloc(void ** ptr_addr, size_t alignment, size_t size)
assuming that I call block alloc in that way:
int a=0;
ptr = &a;
void* ptr_2 = ptr;
ret = block_alloc ( &ptr_2 ,2* sizeof ( void*) , 2* sizeof ( int ) ) ;
I'm doing in block alloc
ptr_addr = malloc ( sizeof (int) );
but when printing the pointer it return the &a location
I need to malloc in a given offset and make all work, any hint on what I'm doing wrong?
CodePudding user response:
As some programmer dude said, you need to change the expression to *ptr_addr = malloc(sizeof(int));, the explanation for it is as follows:
**ptr_addr is a pointer to the pointer that needs to be modified with the allocated space, so reassigning ptr_addr = malloc(sizeof(int)); just modifies your local copy of the pointer to the pointer and creates a leak instead of modifying the pointer that is being pointed to, hence * dereferences the double pointer and allows you to modify the ptr_2 variable.
Also your malloc call is wrong since you're completely disregarding the arguments and allocating the size for a single int only. The correct malloc call would be malloc(size * alignment); assuming alignment is meant to be the initial size of the array (Guessing from "initial index").
CodePudding user response:
Remember the basic pattern:
void update( T *ptr ) // for any type T
{
*ptr = new_T_value; // updates the thing ptr points to
}
void foo( void )
{
T var;
update( &var ); // write a new value to var
}
Now let's replace T with a pointer type P *:
void update( P **ptr )
{
*ptr = new_Pstar_value; // update the thing ptr points to
}
void foo( void )
{
P *var;
update( &var ); // write a new value to var
}
In the second case, var has a pointer type P *, so the input parameter has type P **. But we still want to update the thing ptr points to, so we still write *ptr = ....
So in your case, you would write
*ptr_addr = malloc ( sizeof (int) );
in your block_alloc function, although I think they intend you to allocate memory as
*ptr_addr = malloc( size * alignment );
That allocates enough memory to hold size objects, each of which is alignment bytes wide.
