简体   繁体   English

将内存释放到C中的2d数组

[英]freeing memory to a 2d array in C

So I created a dynamically sized 2d array using the following logic: 因此,我使用以下逻辑创建了动态尺寸的2d数组:

int **newBoard;
newBoard = (int **) malloc(sizeof(int *) * rows);
newBoard[0] = (int *) malloc(sizeof(int) * cols * rows);

for (i = 0; i < rows; i++) {
    newBoard[i] = (*newBoard + cols * i);
}

But now I am having trouble freeing the memory I allocated. 但是现在我无法释放分配的内存。 Whenever I try to I receive a "free(): invalid pointer: 0x00000000007343c8 ***" error message. 每当我尝试接收“ free():无效的指针:0x00000000007343c8 ***”错误消息时。 I am currently trying to free the memory like: 我目前正在尝试释放内存,例如:

for (i = 0; i < rows; i++) {
    free(newBoard[i]);
}
free(newBoard);

Can anyone help me out and tell me how to free this correctly?? 谁能帮助我,告诉我如何正确释放它?

When you do 当你做

newBoard[0] = (int *) malloc(sizeof(int) * cols * rows);

you are allocating a continous block of memory for cols * rows spaces of int objects. 您正在为int对象的cols * rows空间分配连续的内存块。 You can only free it once using the start of the block , you cannot free it at an offset of the start of the memory and you cannot free it multiple times, only once . 您只能使用开始释放一次, 不能在内存开始的偏移量释放它,也不能多次释放它, 只能释放一次

for (i = 0; i < rows; i++) {
    newBoard[i] = (*newBoard + cols * i);
}

Here the newBoard[i] are getting an offset of the continues block of memory, so you cannot free more than once at different offsets, you have to free it once at the start of the block. 在这里, newBoard[i]获得的是连续内存块的偏移量,因此您不能在不同的偏移量处释放一次以上,而必须在该块的开始处释放一次

free(newBoard[0]);
free(newBoard);

would be correct. 是正确的。

Please don't cast malloc , this is bad practice. 请不要malloc ,这是不好的做法。 And you should check if malloc returns NULL . 并且您应该检查malloc返回NULL

I personally think that this is a clever way to do only 2 malloc s instead of row+1 malloc s, but it has downsides, too. 我个人认为这是只执行2个malloc而不是row+1 malloc的聪明方法,但是它也有缺点。 You have to be very careful with it. 您必须非常小心。 Freeing single blocks of memory that are not needed is not possible, reallocation of single newBoard[i] is also not possible. 释放不需要的单个内存块是不可能的,单个newBoard[i]重新分配也是不可能的。 You have to have a lot of discipline in order to avoid mistakes like multiple free s, that's why I think that the traditional way of doing, is better overall. 为了避免像多个free这样的错误,您必须要有很多纪律,这就是为什么我认为传统的总体做法更好。 I'd do: 我会做:

for(i = 0; i < rows; ++i)
    newBoard[i] = malloc(cols * sizeof *newBoard[i]);

then you can free like you did. 那么您可以像以前一样自由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM