Q:

How can you determine the size of an allocated portion of memory?

0

How can you determine the size of an allocated portion of memory?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

In C language, we can calculate the size of the static array using the sizeof operator but there is no operator to calculate the size of the dynamically allocated memory. So using some trick we can get the size of the allocated array. Mainly there are two ways to get the size of allocated memory in every section of the code.

  • Create a global variable to store the size of the allocated memory.
  • Carry the length of allocated memory.

Let see an example code, where I am explaining how you can carry the length of the array. So suppose you need to create an integer array whose size is n. So to carry the array length of the array, you need to allocate the memory for n+1.

int *piArray = malloc ( sizeof(int) * (n+1) );

If memory is allocated successfully, assign n (size of the array) its 0 places.

piArray[0] = n;
     or
* piArray = n;

Now it’s time to create a copy of the original pointer but to left one location from the beginning.

//Left 0th location
int * pTmpArray = piArray +1;

Note: if you are new, see this article arithmetic operation on the pointer.

Now, whenever in a program you require the size of the allocated dynamic, you get from the temporary pointer(copy pointer).

//Getting size of the allocated array
int ArraySize = pTmpArray[-1];

After using the allocated memory don’t forget to deallocate the allocated memory.

free (piArray);

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

What is the purpose of realloc( )?... >>
<< Is it better to use malloc () or calloc ()?...