如何解决为什么 valgrind 在我的程序中没有显示明显的泄漏?
当我编译一个使用了 malloc 两次的程序时,我意识到我在程序结束时忘记释放分配的内存。
最近遇到了 Valgrind 工具,我认为这是运行它以查看它如何显示内存泄漏错误的好机会。但令我惊讶的是,Valgrind 返回所有堆块都被释放了......
我唯一能想到的就是 malloc 不在主函数中,而是在从属函数中。但我不认为 Valgrind 会被限制在 main 上,是吗
我试图在 Valgrind 文档中找到答案,但无济于事。
这是请求的完整代码,其目的是通过用户提供的 26 个字母的密钥作为命令行参数来加密文本。
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
void cipher(char *,char *);
int main(int argc,char *argv[])
{
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
//INPUT
char *p = get_string("plaintext: ");
//OUTPUT
cipher(argv[1],p);
return 0;
}
void cipher(char *a,char *b)
{
char *low = malloc(27 * sizeof(char));
for (int i = 0; i < 27; i++)
{
if (islower(a[i]))
{
low[i] = a[i];
}
else
{
low[i] = (a[i] + 32);
}
}
char *upp = malloc(27 * sizeof(char));
for (int i = 0; i < 27; i++)
{
if (isupper(a[i]))
{
upp[i] = a[i];
}
else
{
upp[i] = a[i] - 32;
}
}
printf("ciphertext: ");
for (int i = 0,l = strlen(b); i < l; i++)
{
if (islower(b[i]))
{
printf("%c",low[(int)b[i]-97]);
}
else if (isupper(b[i]))
{
printf("%c",upp[(int)b[i]-65]);
}
else
{
printf("%c",b[i]);
}
}
}
解决方法
在所有这些评论之后,答案有点愚蠢......
您的屏幕截图显示您运行了 valgrind ./substitution
,而没有向您的程序传递任何命令行参数。当这种情况发生时,它打印 Usage: ./substitution key
并退出而不做任何进一步的事情;特别是没有调用 cipher()
,因此也没有调用 malloc()
。所以在这种情况下当然没有内存泄漏。
如果您在命令行中使用 key 参数运行程序,并为其提供一些输入,您应该看到 valgrind
报告内存泄漏:
==15815==
==15815== HEAP SUMMARY:
==15815== in use at exit: 54 bytes in 2 blocks
==15815== total heap usage: 4 allocs,2 frees,2,102 bytes allocated
==15815==
==15815== LEAK SUMMARY:
==15815== definitely lost: 54 bytes in 2 blocks
==15815== indirectly lost: 0 bytes in 0 blocks
==15815== possibly lost: 0 bytes in 0 blocks
==15815== still reachable: 0 bytes in 0 blocks
==15815== suppressed: 0 bytes in 0 blocks
==15815== Rerun with --leak-check=full to see details of leaked memory
尽管原则上编译器可以优化 malloc
调用,但在我使用 gcc 和 clang 使用 -O3
进行的测试中,我找不到任何迹象表明它们确实这样做了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。