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("
block size (for a): %p-%p : %li", b, a, b-a);
a = malloc(1024);
b = malloc(1024);
printf("
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("
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…