简体   繁体   English

Memory C (MacOS) 中的泄漏

[英]Memory Leaks in C (MacOS)

I'm a C programming student trying to find a way to detect memory leaks on MacOs Mojave.我是一名 C 编程学生,试图找到一种方法来检测 MacOs Mojave 上的 memory 泄漏。

I know about the existence of Valgrind, but it doesn't support current MacOs releases.我知道 Valgrind 的存在,但它不支持当前的 MacOs 版本。 After installing Apple Command Line Tools, I tried to run my C program with leaks tool but it doesn´t work... Running this very simple C program:安装 Apple 命令行工具后,我尝试使用泄漏工具运行我的 C 程序,但它不起作用......运行这个非常简单的 C 程序:

#include <stdio.h>

int main(int argc, char const *argv[]) {
  printf("Hello World\n");
  return 0;
}

Like this:像这样:

leaks ./a.out

This is the output:这是 output:

leaks[875]: [fatal] unable to read input graph: The data 
 couldn’t be read because it isn’t in the correct format.

I don´t understand why this happens... How can I use the leaks tool?我不明白为什么会发生这种情况......我如何使用泄漏工具?

i'm not sure is this helpful, but if the C program's status is in running, "leaks" would be available我不确定这是否有帮助,但如果 C 程序的状态为正在运行,则“泄漏”将可用

#include <stdio.h>

int main(int argc, char const *argv[]) {
  printf("Hello World\n");
  getchar(); // just add to sleep
  return 0;
}

run above, then run belows in another terminal在上面运行,然后在另一个终端运行下面

leaks a.out

you can show related messages您可以显示相关消息

Process:         a.out [8724]
Path:            /Users/USER/Documents/*/a.out
Load Address:    0x1078f2000
Identifier:      a.out
Version:         ???
Code Type:       X86-64
Parent Process:  bash [7876]
...

using [PID] is also available in this example在这个例子中也可以使用 [PID]

leaks 8724

here is a sample code that memory leak is detected,这是检测到 memory 泄漏的示例代码,

#include <stdio.h>

void test()
{
  char* pTmp = (char*)malloc(sizeof(char)*1);
}

int main(int argc, char const *argv[]) {
  printf("Hello World\n");
  test();
  getchar();
  return 0;
}

Try this尝试这个

#define malloc(X) my_malloc( X, __FILE__, __LINE__, __FUNCTION__)

void* my_malloc(size_t size, const char *file, int line, const char *func)
{

    void *p = malloc(size);
    printf ("Allocated = %s, %i, %s, %p[%li]\n", file, line, func, p, size);

    /*Link List functionality goes in here*/

    return p;
}

Unlike Valgrind, the leaks command is designed to find memory leaks in code that is already running when the "leaks" command is executed.与 Valgrind 不同,leaks 命令旨在查找 memory 在执行“leaks”命令时已经运行的代码中的泄漏。

In order to get the functionality you are looking for you want the following command:为了获得您正在寻找的功能,您需要以下命令:

leaks -atExit -- ./a.out

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM