c - 如何检查我的 C 代码使用的内存?

标签 c memory

我是一名新的 C 程序员,指针 + 数组让我很困惑。我没有收到任何错误并且代码运行良好......直到代码在中间的某个地方开始起作用,因为数组中的某些元素被设置为我想要的以外的东西。我想知道有没有程序运行完后可视化代码的内存?

例如在我运行之后:

#include<stdio.h>
int main(){
    int array[2] = {0,1};
    array[1] = 4;
    printf("%d\n",array[1]);
    }

它将显示一个内存块,其中数组有两个元素 0 和 4。

现在,为了避免遇到数组包含来自先前操作的元素的问题,我通过执行以下操作清除了该数组的内存:

memset(tokenized,0,MAX_CHARS);

它似乎有效,但我不知道它是否真的在做我认为它在后端做的事情。

编辑: 我现在正在使用 Valgrind,我只想知道,我怎么知道错误指的是哪一行? 例如我得到这个:

==24394== Source and destination overlap in strncpy(0x7ff000006, 0x7ff000006, 6)
==24394==    at 0x4C2C236: strncpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==24394==    by 0x400D8A: tokenize_quotes (in /home/zee/Documents/seng265/repos/assignment2/a.out)
==24394==    by 0x40184E: main (in /home/zee/Documents/seng265/repos/assignment2/a.out)
==24394== 
==24394== Conditional jump or move depends on uninitialised value(s)
==24394==    at 0x4C2C007: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==24394==    by 0x400E06: tokenize_quotes (in /home/zee/Documents/seng265/repos/assignment2/a.out)
==24394==    by 0x40184E: main (in /home/zee/Documents/seng265/repos/assignment2/a.out)
==24394== 

但是不知道错误在哪一行?我知道它是关于 strcpy 的 谢谢!

最佳答案

使用Valgrind :

Valgrind is a GPL'd system for debugging and profiling Linux programs. With Valgrind's tool suite you can automatically detect many memory management and threading bugs, avoiding hours of frustrating bug-hunting, making your programs more stable. You can also perform detailed profiling to help speed up your programs.​

关于c - 如何检查我的 C 代码使用的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11081032/

相关文章:

java - 什么是好的 java 调试器?

java - `+=` 运算符是否总是创建一个新的字符串对象?

linux - 在linux中获取短运行程序的峰值内存(堆和堆栈)

c++ - 在 Linux 中设置编程环境

c - 如何设置指向结构的 Gtk gpointer?

c - 了解进程的执行环境

我们可以返回非指针函数的值吗

c - 内存泄漏检测分析工具

python - 如何在 python 中使用 c 结构?

iphone - iOS 允许应用使用多少内存?