0

下面的代码会导致 C++ 在行上崩溃:free(arg)。我试图防止发生内存泄漏,但我无法释放我存储在堆内存中的数据。有人可以帮我解决这个问题吗?

请注意,free(args)工作正常。

#include "stdafx.h"
#include <process.h>
#include <iostream>

#include <windows.h>

using namespace std;

typedef struct {
    int StartNode;
    int EndNode;
}t;
t *arg;

void myFunc(void *param) {
    t *args = (t*)param;
    int x = args->StartNode;
    int y = args->EndNode;
    printf("x=%d, y=%d\n", x, y);
    free(args);
    free(arg);
}

int main()
{
    HANDLE handle;
    arg = (t *)malloc(sizeof(t));
    arg->StartNode = 101;
    arg->EndNode = 103;
    handle = (HANDLE)_beginthread(myFunc, 0, (void*)arg);
    cin.get();
    return 0;
}
4

3 回答 3

0

args 和 arg 都指向相同的内存位置。免费呼叫任何人就足够了。

于 2020-11-30T19:53:23.497 回答
-2

您的两个指针分别指向相同的内存位置,args并且arg您试图两次释放相同的内存位置,这会在此处产生问题。请看下面:-

 free(args); //args->arg here args is pointing to arg you have just type cast it from void
 free(arg);//you have already release the memory in the above call so this is wrong

只是尝试这样理解,下面的示例不是解决方案,而是为了您的理解。您在这里分配args = NULL,这将反映在arg = NULL因此if(arg != NULL)将是错误的,因此free(arg);不会被调用。:-

free(args); 
args = NULL;
if(arg != NULL)
  free(arg);
于 2018-03-28T17:01:52.703 回答
-2

免费调用的次数需要和malloc一样。你只 malloc 一次,在

arg = (t *)malloc(sizeof(t));

但是您两次释放相同的地址:

free(args);
free(arg);

现在,这是 C 代码,而不是 C++(作为 C++,您将使用 new / delete,或者更好的是,您不会使用 nor new 或 delete,并通过堆栈中的引用传递变量,如下所示:

#include <iostream>
#include <windows.h>

struct MyType {
    int StartNode;
    int EndNode;
};

void myFunc(const MyType &param) {
    const auto x = args.StartNode;
    const auto y = args.EndNode;
    std::cout << "x=" << x << ", y=" << std::endl;
}

int main()
{
    auto arg = MyType{};
    arg.StartNode = 101;
    arg.EndNode = 103;
    std::thread thread(myFunc, arg);
    thread.join();
    cin.get();
    return 0;
}

一些随机笔记:

  • 您将 C 与 C++ 混合在一起,它们不是同一种语言
  • 您正在使用仅限 Windows 的调用,请使用 std(如在线程示例中)
  • 不要使用 using namespace std; 这使代码立即变得不可读。
于 2018-03-28T17:06:33.277 回答