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

28 Dec 2022 Balmiki Mandal 0 C Programming

Determining the Size of Allocated Memory in C: Tips and Tricks

There are two ways to determine the size of an allocated portion of memory in C:

Use the sizeof() operator:

 The sizeof() operator returns the size of a data type or variable in bytes. For example, the following code will print the size of an integer variable to the console:

C programming
int main() {
  int num;

  printf("The size of an integer is %d bytes.\n", sizeof(num));

  return 0;
}

Output:

The size of an integer is 4 bytes.

We can also use the sizeof() operator to determine the size of an allocated portion of memory. For example, the following code will print the size of an array of 10 integers to the console:

C Programming
int main() {
  int arr[10];

  printf("The size of the array is %d bytes.\n", sizeof(arr));

  return 0;
}

Output:

The size of the array is 40 bytes.

Use the malloc_size() function: 

The malloc_size() function returns the size of an allocated portion of memory that was allocated using the malloc() function. For example, the following code will allocate 10 bytes of memory and then print the size of the allocated memory to the console:

C program
#include <stdlib.h>

int main() {
  void* ptr = malloc(10);

  printf("The size of the allocated memory is %d bytes.\n", malloc_size(ptr));

  free(ptr);

  return 0;
}

Output:

The size of the allocated memory is 10 bytes.

It is important to note that the malloc_size() function is not available in all C compilers. If your compiler does not support the malloc_size() function, you can use the sizeof() operator to determine the size of an allocated portion of memory.

 

Which method you use to determine the size of an allocated portion of memory depends on your specific needs. If you need to determine the size of a data type or variable, you should use the sizeof() operator. If you need to determine the size of an allocated portion of memory that was allocated using the malloc() function, you should use the malloc_size() function.

Top Resources

What is static memory allocation and dynamic memory allocation?

What is a memory leak in c ?

How to array are in the contiguous memory location.

Further Reading:

 For further information and examples, Please visit[ C-Programming From Scratch to Advanced 2023-2024]

 

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.