提问人:studentofquran 提问时间:3/18/2023 最后编辑:studentofquran 更新时间:3/19/2023 访问量:47
在 C 中创建 2D 数组时检查 malloc 失败 [已关闭]
Checking for malloc failure when creating a 2D array in C [closed]
问:
我正在尝试检查创建 2D 数组时是否分配错误失败。这是我想出的:
...
image->imageData = (unsigned int**) malloc(image->height * sizeof(unsigned int*));
// if malloc is unsuccessful, it will return a null pointer
if (image->imageData == NULL) { // check malloc
image->errorStatus = BAD_MALLOC;
return image;
} // check malloc
for(int nRow = 0; nRow < image->height; nRow++) {
image->imageData[nRow] = (unsigned int*) malloc(image->width * sizeof(unsigned int));
// if malloc is unsuccessful, it will return a null pointer
if (image->imageData[nRow] == NULL) { // check malloc
image->errorStatus = BAD_MALLOC;
return image;
} // check malloc
}
...
malloc 失败的情况是图像尺寸过高(image->height 和 image->width),导致程序内存不足。我知道这个代码片段无法检测到它,因为当我复制案例时,image->errorStatus 被设置为其他内容(在程序的下方)。我的问题是为什么这个代码片段无法检测到 malloc 故障。
答:
2赞
chqrlie
3/18/2023
#1
如果某行的分配失败,则应释放到目前为止分配的内存并返回 。如果被分配,则应释放它并返回 。NULL
image
NULL
struct Image *alloc_iamge(int heigth, int width) {
struct Image *image = calloc(1, sizeof(*image));
if (image == NULL)
return NULL;
image->height = height;
image->width = width;
image->imageData = malloc(image->height * sizeof(unsigned int*));
// if malloc is unsuccessful, it will return a null pointer
if (image->imageData == NULL) { // check malloc
free(image);
return NULL;
}
for (int nRow = 0; nRow < image->height; nRow++) {
image->imageData[nRow] = calloc(image->width, sizeof(unsigned int));
// if malloc is unsuccessful, it will return a null pointer
if (image->imageData[nRow] == NULL) {
while (nRow > 0) {
free(image->imageData[--nRow]);
image->imageData[nRow] = NULL;
}
free(image->imageData)
image->imageData = NULL;
free(image);
return NULL;
}
}
return image;
}
如果内存分配失败,或者将返回 .在现代操作系统上,如果分配大小超过进程可用的配额,则会发生这种情况。如果成功,内存可能被访问,但可能还不可用:内存可能被过度使用,即:页面将在稍后写入时映射到进程地址空间,并且将根据需要回收相同或另一个进程的其他一些页面。代码页和文件缓存页将被重用,数据页将被写入交换文件以供以后重新加载。其他内存管理技术可用于优化内存使用,例如内存压缩(例如:macOS)。malloc
calloc
NULL
malloc
评论
0赞
studentofquran
3/18/2023
这在我的代码中的其他位置处理。
0赞
0___________
3/18/2023
对 calloc 的良好更改将分配内存,而不仅仅是承诺它。
0赞
chqrlie
3/18/2023
@studentofquran:以上是一个用于分配图像结构的独立函数。您应该为基本任务编写函数,并发布显示问题的完整程序。
0赞
chqrlie
3/18/2023
@0___________:恐怕在过度投入方面没有区别。对于大量内存,在有效写入内存之前,它不会进行映射。malloc
calloc
0赞
0___________
3/18/2023
我相信@chqrlie卡洛克应该写它
评论
malloc