我有这段代码
#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);
}
这不应该打印最后分配的块大小(16 或 1024)吗?它改为打印 24 和 1032,因此分配的内存量似乎有 8 个额外字节。
我的问题是(在制作这个测试用例之前)我malloc()
在一个函数(1024 字节)中执行,并返回分配的结果。当检查函数返回的块大小时,我得到 516 个块......我不明白为什么。我想这可能是对分配的缓冲区进行一些处理后发生内存损坏的原因:)
编辑:我已经看到如何从 C 中的指针获取数组的大小?似乎问同样的事情,抱歉重新发布。
我已将示例重做为更具体的代码:
#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;
}
输出是
block size (for a): 0x804a420-0x804a018 : 516
block size (for a): 0x804a828-0x804a420 : 516
block size (for a): 0x804ac30-0x804a828 : 516
根据上面的帖子大于1024。我错了吗?