释放char数组时的内存泄漏 [英] Memory Leak when freeing a char array

查看:868
本文介绍了释放char数组时的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经分配了一个char数组并对其进行了初始化:

I have malloc a char array and initialize it:

int i;
int length = 100;
char *arr = (char *) malloc (length * sizeof(char));
for (i = 0; i < length; i++) {
    arr[i] = i;
}

然后将中间字符设置为'\ 0':

then I set the middle char to '\0':

arr[50] = '\0';

在这种情况下,arr仅具有无效长度50,而不是100 然后我使用免费:

In this case, arr only has invalid length 50, not 100 then I use free:

free(arr);

这会导致内存泄漏吗?即操作系统将记录malloc的长度还是仅使用strlen来判断长度?

can this cause memory leak? ie the operating system will record the malloc length or just use strlen to judge the length?

推荐答案

否.内存的内容对free()的工作方式没有影响.

No. the contents of the memory has no impact on how free() works.

free()不知道您将其用作以null终止的char字符串.永远不会在一块内存上使用strlen().

free() doesn't know you were using this as a null terminated char string. It would never use strlen() on a chunk of memory.

尝试使用valgrind之类的工具来检查代码是否泄漏.

Try a tool like valgrind to check your code for leaks.

这篇关于释放char数组时的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆