'How can I find the difference between two memory addresses allocated by malloc?

First things first, this is for a college class. The problem is to run malloc 1001 times with size 4, storing each returned pointer as a char *, then get the different between the first and last pointer to calculate total memory used. The instructions also state this number will be much higher than one might expect.

This is what I have so far, but I don't think it is working properly(and even it is I would appreciate if someone could show me how to do it more efficiently):

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

int main()
{
  // Init variables
  int size = 4;
  char *ptrs[1001];

  // Allocate memory
  for (int i = 0; i <= 1001; i++)
  {
    ptrs[i] = malloc(size);
  }

  // Get first and last address
  int *first_ptr = (int*)&ptrs[0];
  int *last_ptr = (int*)&ptrs[sizeof(ptrs) / sizeof(*ptrs) - 1];
  int diff = (int)last_ptr - (int)first_ptr;

  // Print first and last address
  printf("First pointer's address: %d\n", first_ptr);
  printf("Last pointer's address: %d\n", last_ptr);
  printf("Memory used: %d\n", diff);

  free(*ptrs);

  return 0;
}

So far the first and last addresses are always large negative values(this could be fine, I'm not certain), and the difference is always 4000, even if I change size to 16 or 32.

Any help would be greatly appreciated.



Solution 1:[1]

Your code has errors:

Following cycle should have this condition: i < 1001 and not i <= 1001 as char *ptrs[1001] have 1001 elements (indexed form 0 to 1000) and not 1002.

  // Allocate memory
  for (int i = 0; i <= 1001; i++)
  {
    ptrs[i] = malloc(size);
  }

If you want to know difference between addresses of allocated memory and not of elements of your array then just use values of your array:

int difference = (int)(ptrs[1000] - ptrs[0])

In your case you are calculating difference between addresses in array and it dependent on size of array element (size of pointer) and not on contents of its elements

  // Get first and last address
  int *first_ptr = (int*)&ptrs[0];
  int *last_ptr = (int*)&ptrs[sizeof(ptrs) / sizeof(*ptrs) - 1];

Difference between first and last element is not guaranteed to be actual used memory size. It depends on how memory allocation works.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 medelist