Home > front end >  I don't understand pointers in dynamic memory allocation
I don't understand pointers in dynamic memory allocation

Time:08-22

Memory dynamically allocated using malloc is done like this:

int *ptr=(int*)(malloc(sizeof(int)))

I don't understand why pointer is used before malloc in (int*) and why we have another pointer with int *ptr.

I am sorry to put up this basic question here and bother people here with this one. But I am not clear after googling this and need help.

Thank You.

CodePudding user response:

  1. malloc allocates space for an int using sizeof(int).

  2. malloc returns a pointer, which is converted to int * using (int*).

  3. Finally, it assigns that pointer to ptr, which could also be written as

    int* ptr =

  4. Now ptr has the value from malloc.

There is no difference in

int *ptr=(int*)(malloc(sizeof(int)));

and

int* ptr=(int*)(malloc(sizeof(int)));

but in my opinion, the second one is clearer, because it has the same notation as the cast.

As the commenter said, it can be simplified to:

int* ptr=malloc(sizeof(int));

which, to me, is the clearest and simplest of all. Hope this helps!

CodePudding user response:

The (int *) before the malloc call is a cast - it means "convert the return value of malloc to type int * before assignment".

With one exception, different pointer types cannot be directly assigned to each other - you cannot assign a char * value to an int * object or vice versa without an explicit cast. Prior to the 1989 version of the C language definition (C89), malloc, calloc, and realloc all returned char *, so if you wanted to assign the result to a different pointer type, a cast was always necessary:

int *foo = (int *) malloc( N * sizeof *foo);
double *bar = (double *) calloc( N, sizeof *bar );
struct s *blurga = (struct s *) realloc( bletch, 2 * N * sizeof *blurga );

This, as you can imagine, was a pain in the ass.

To help solve this and several other problems, C89 introduced the void type, along with a special rule that allows you to assign void * values to other pointer types and vice versa without an explicit cast. It also changed the *alloc functions to return void *, so those calls can now be written as

int *foo = malloc( N * sizeof *foo );
double *bar = calloc( N, sizeof *bar );
struct s *blurga = realloc( bletch, 2 * N * sizeof *blurga );

void is an empty type with no size and no values, so you can't dereference a void * or do pointer arithmetic on it, but you can use it as a "generic" pointer type to store pointer values without really caring about the type of the pointed-to object.

Note that C does not allow void * values to be assigned to other pointer types without a cast, so you'd still need the cast for malloc calls, but it you're writing C you shouldn't be using malloc anyway.

  •  Tags:  
  • c
  • Related