在 C 中释放多维数组
假设我们有:
void createMultiArray(){
int i,j;
char*** codes = malloc(5 * sizeof(char**));
for ( i = 0; i <= 4; i++ ) {
codes[i] = malloc((i+1) * sizeof(char*));
for ( j = 0; j <= i; j++ ) {
codes[i][j] = malloc(2 * sizeof(char));
}
}
我应该如何释放代码
?
free(codes);
或者
int i,j;
for(i = 0; i <=4; i++){
for(j = 0; j <= i; j++){
free(codes[i][j]);
}
free(codes[i]);
}
free(codes);
Let's say we have:
void createMultiArray(){
int i,j;
char*** codes = malloc(5 * sizeof(char**));
for ( i = 0; i <= 4; i++ ) {
codes[i] = malloc((i+1) * sizeof(char*));
for ( j = 0; j <= i; j++ ) {
codes[i][j] = malloc(2 * sizeof(char));
}
}
How should I free codes
?
free(codes);
or
int i,j;
for(i = 0; i <=4; i++){
for(j = 0; j <= i; j++){
free(codes[i][j]);
}
free(codes[i]);
}
free(codes);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这样想 - 每个
malloc
都应该有一个free
。所以是的,你的第二个选择是正确的。
Think about it this way - you should have a
free
for everymalloc
.So yes, your second option is the correct one.
第二个是你想要的,
free
不能也不会递归地工作。每次执行malloc
时,请考虑将要调用free
的位置。附带说明一下,如果您接下来要退出程序,请不要释放内存 - 这是毫无意义的,并且可能需要相当长的时间。
The second one is what you want,
free
can't and won't work recursively. Each time when you do amalloc
think of the place where you're going to callfree
.As a side note, don't free the memory if the next thing you'll do is exit the program - it's pointless and could take quite a bit of time.
第二个是正确的,而第一个会泄漏内存。根据经验,您希望为每个
malloc()
调用调用free()
。The second is correct, while the first one leaks memory. As a rule of thumb, you want to call
free()
for everymalloc()
call.如果您可以事先计算数组的大小,最好不要使用嵌套的 malloc()-s。您应该一步完成分配和释放(让您的生活更轻松并减少出现错误的机会)。
Preferably you don't use nested malloc()-s, if you can calculate the size of the array beforehand. You should allocate and free in one step ( making your life easier and reducing the chance of bugs ).
createMultiArray()
的内存布局如下:现在,返回并释放使用 free 创建的每个内存 [是的,对于每个
malloc()
应该有成为一个free()
]OTOH,您确定要这样做吗?
这是故意的吗?
The memory layout for
createMultiArray()
would be as follows:Now, go back and free each memory you've created using free [yeah, for each
malloc()
there should be afree()
]OTOH, are you sure you want to do this?
Is this intentional?
不要使用如此复杂的分配方案来模拟多维数组。特别是在您的情况下,所有界限都是编译时间常量。
实现相同的目的,
最后只需要一个。如果您使用该数组的上下文甚至绑定到一个范围并且您的范围很小,您甚至可以将其直接分配为 auto 变量,甚至同时初始化它,而
无需在最后释放。
Don't use such complicated allocation schemes to emulate multidimensional arrays. In your case in particular, where all bounds are compile time constants.
fulfills the same purpose and only needs one
at the end. If the context where you use that array is even bound to one scope and your bounds are small you could even allocate it directly as
auto
variable and even initialize it at the same timeno need to free at the end.