Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand the syntax of two functions malloc() and calloc() exactly

I'm studying C and have some question about dynamic memory allocation syntax.

The code below is an example of dynamic memory allocation. If I understand correctly

 (char *) malloc (50 * sizeof (char));

will return a pointer to a data type of char and

  pr = (char *) malloc (50 * sizeof (char));

will assign the pointer 'pr' to the pointer declared when allocating dynamic memory. So we will have a pointer point to another pointer

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char *pr;

   pr = (char*)malloc( 50 * sizeof(char) ); 

   return 0;
}

I still have a hard time understanding the syntax used to allocate dynamic memory. Can someone explain in detail? thank you

like image 325
Quốc Cường Avatar asked Mar 04 '23 23:03

Quốc Cường


1 Answers

will assign the pointer 'pr' to the pointer declared when allocating dynamic memory. So we will have a pointer point to another pointer

No, you'll have the value of the pointer variable stored.

This is just the same as

int x = 5;

or, in a more complex case

int test(void) { return 5;}
int x = test();

in this case, test() returns a value 5, which is assigned to x. Same way

char * pr = malloc (50 * sizeof (*pr));  // no casting, and sizeof (*pr) is a
                                         // more robust way to have the size defined 

assigns the returned pointer by malloc() to pr. There's no pointer to pointer here.

In other words, pr holds the pointer which points to the memory location allocated by the call to malloc(), or a NULL (null-pointer constant) in case the call failed.

like image 68
Sourav Ghosh Avatar answered Mar 15 '23 23:03

Sourav Ghosh