How can you determine the size of an allocated portion of memory?
belongs to collection: 10 Questions on dynamic memory allocation in C
All Answers
total answers (1)
belongs to collection: 10 Questions on dynamic memory allocation in C
total answers (1)
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.
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.
If memory is allocated successfully, assign n (size of the array) its 0 places.
Now it’s time to create a copy of the original pointer but to left one location from the beginning.
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).
After using the allocated memory don’t forget to deallocate the allocated memory.
need an explanation for this answer? contact us directly to get an explanation for this answer