malloc之后的自由函数出错

时间:2018-03-28 16:53:34

标签: c++ malloc free beginthread

以下代码导致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;
}

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-2)

您的两个指针argsarg分别指向相同的内存位置,并且您尝试两次释放相同的内存位置,并在此处创建问题。请参阅以下内容: -

 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)将为false,因此free(arg);将不会被调用。: -

free(args); 
args = NULL;
if(arg != NULL)
  free(arg);

答案 2 :(得分:-2)

免费通话的数量需要与malloc相同。 在

中只对一次conde malloc
arg = (t *)malloc(sizeof(t));

但你两次释放同一地址:

free(args);
free(arg);

现在,这是C代码,而不是C ++(作为C ++,你会使用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(如线程示例中所示)
  • 不要使用namespace std;这使得代码很快就无法读取。