0

I allocated memory:

int *p = (int *) malloc(sizeof(int));

Then I typcase it:

char *new = (char *)p;

I deallocate it:

free(new);

1) How much memory will be deallocated as character has 1 byte of space? 2) what internal mechanism should a memory manager make (in embedded system) to keep track of allocated memory and deallocated memory? (no Boolean allowed)

hmjd
  • 120,187
  • 20
  • 207
  • 252
user2071394
  • 31
  • 1
  • 4
  • `malloc()` and `free()` deal with `void* and have no idea about the type - they just deal with blocks of memory of the size you ask for. – Michael Burr Feb 20 '13 at 10:44

2 Answers2

1

When you call malloc (or one of it's siblings), the size of the memory allocate it stored as part of the 'information about this allocation' (info_block). malloc doesn't know if you passed in sizeof(int), the constant 4 or sizeof(short)*2 or whatever else you may have given it [actually, it may well expand the allocation to, say, 16 bytes - and this size is stored as part of the allocation.

When you later call free, it will "find back" the info_block, and then it knows the size to free. So, it doesn't matter what casts, or other manipulations you do on the pointer - as long as the pointer inside is the same value.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • I want to avoid look ups, like I am writing a new memory managers and there are no undesired lookups/Boolean/size storage – user2071394 Feb 20 '13 at 11:45
  • The "lookup", in all allocators I've looked at, is as simple as "subtract sizeof(info) from the pointer we got", so it's not a long operation at all. Some allocators then tries to merge the previous/next block of free memory to the current one, but not always. If fragmentation is an issue, using a set of "buckets" of a fixed number of sizes is a good way to avoid that. – Mats Petersson Feb 20 '13 at 12:08
0

I your specific case, the answer depends on the underlying architecure. Assuming a 32-bit machine, the size of a pointer is always 4 bytes. It could get troublesome if you used, i.e.

int *p = (int *) malloc(sizeof(char));

but you'll get a warning, I believe.

So in your case it is 4 bytes that become allocated.

Additionally you should not cast the void* from malloc:

int *p = malloc(sizeof(int));

is perfectly fine.

bash.d
  • 13,029
  • 3
  • 29
  • 42