-
Memory to be deallocated
Hi All,
I have written the following code.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *a, *b;
a = (int*) malloc (sizeof(int) * 10);
printf ("%d\n", a[-1]);
b = (int*) malloc (sizeof(int) * 15);
printf ("%d\n", b[-1]);
return 0;
}
I have written many mallocs and printed the '-1' Index of the each allocated memory. The output for the previous one comes as follows:
I have observed that it actually shows how much memory it has allocated.
Code:
For the 10(even) allocations, It allocates space for
10 Integers (4 * 10 = 40 bytes) + One 4 bytes space for -1 Index Itself + 1 (4 bytes) after the array
= 40 + 4 + 4 = 48
And It adds 1 extra byte. (I don't know why?) Hence It prints = 49.
Code:
Similarly, for 15(odd) allocations, It allocates space for
15 Integers(4*15 = 60 bytes) + One 4 bytes space for -1 Index Itself = 60 + 4 = 64 bytes
And It adds 1 extra byte. (I don't know why?) Hence It prints = 65.
Why does It add an extra byte? This is my question.
Thanks and Best Regards,
Aakash Johari
-
Why do you believe anything you've written?
You have tested exactly ONE permutation of
- Operating system ( type and version )
- Compiler ( type and version )
- Compiler options
- Standard library version
Change anything, and you're looking at
- the same answer
- a different answer
- a segmentation fault
Like your other thread, it is very machine dependent.
If you really want to know what it actually is (rather than guess from a few experiments), then download the GlibC source code and read malloc.c