gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:53:00 25 4
gpt4 key购买 nike

我是一名新的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com