I have this piece of code
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> int main(){ void *a, *b; a = malloc(16); b = malloc(16); printf('\n block size (for a): %p-%p : %li', b, a, b-a); a = malloc(1024); b = malloc(1024); printf('\n block size (for a): %p-%p : %li', b, a, b-a); }
Shouldn’t this print the last allocated block size (16 or 1024)? It instead prints 24 and 1032, so the amount of memory allocated seems to have 8 extra bytes.
My problem is (before making this test case) that I do malloc() in a function (1024 bytes), and return the allocated result. When checking the block size on the function return I get 516 blocks… and I don’t understand why. I guess this might be the reason for the memory corruption that occurs after doing some processing on the allocated buffers:)
Edit: I’ve seen How can I get the size of an array from a pointer in C? and seems to ask the same thing, sorry for reposting.
I’ve redone my example to my more specific code:
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> short int * mallocStuff(long int number, short int base){ short int *array; int size=1024; array=(short int*)calloc(1,size); //array=(short int*)malloc(size); return array; } int main(){ short int **translatedArray; translatedArray=malloc(4*sizeof(short int)); int i; for(i=0;i<4;i++){ translatedArray[i]=mallocStuff(0,0); if(i>0) printf('\n block size (for a): %p-%p : %i', translatedArray[i], translatedArray[i-1], translatedArray[i]-translatedArray[i-1]); } return 0; }
And the output is
block size (for a): 0x804a420-0x804a018 : 516 block size (for a): 0x804a828-0x804a420 : 516 block size (for a): 0x804ac30-0x804a828 : 516
According to the above post that is bigger than 1024. Am I wrong?
You have a bug. Instead of:
You should have
Note the missing pointer in your code. I suspect this is where your observed behavior stems from.
Also notice that
0x804a420 - 0x804a018 = 1032, not516. The formulatranslatedArray[i] - translatedArray[i - 1]gives you the number of elements (short ints, or more simply, shorts) in between the two addresses, not the number of bytes.