我在 Xcode 中使用 malloc 分配内存时遇到问题
当我使用较小的Block_size(256)时代码没有问题 如果我使用更大的 Block_size (65536),Xcode 将停止在“state1[t] = (int*) malloc(sizeof(int) * 4);”并告诉我 BAD_ACCESS。如何解决这个问题?
谢谢
int main(int argc, const char * argv[]) {
// insert code here...
int **state1;
int t = 0;
int Block_size = 65535;
state1 = (int **)malloc(sizeof(int) * Block_size);
printf("%d",Block_size);
for (t=0 ; t < Block_size-1 ; t++) {
state1[t] = (int*) malloc(sizeof(int) * 4);
}
printf("end");
return 0;
}
最佳答案
第一个 malloc 应该是
state1 = malloc(sizeof(int *) * Block_size);
因为您分配了一个指针数组。在 64 位平台上,这会有所不同! 有些人更喜欢写
state1 = malloc(sizeof(*state1) * Block_size);
避免此类错误。
备注:在 C 语言中,您无需转换 malloc()
的返回值。
关于c - 奇怪的 malloc 访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18272853/