Remix.run Logo
simiones an hour ago

Well, even that doesn't really work, because optimized allocators typicallly don't allocate exactly the amount that you ask for, they allocate some larger chunk to help with both alignment and fragmentation.

So, most likely, there are two sizes in reality: the size of your user data that you care about; and the size of the memory chunk in which your user data resides, that free() cares about. So, unless you're willing to go for an API like this, you can't rely on the consumer:

  int* ptr_to_dest = NULL;
  size_t size = 10 * sizeof(int);
  size_t allocated = malloc(&ptr_to_dest, size);
  if (allocated <= 0 || !ptr_to_dest) {
    //handle allocation error
  }
  //... use ptr_to_dest, size
  free(ptr_to_dest, allocated); //careful not to pass size here!