以下代码在行上导致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=%dn", 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;
}
ARG和ARG都指向同一内存位置。任何人都可以免费打电话。
您的两个指针分别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);
免费呼叫的数量必须与malloc相同。您只会在
中使用一次condearg = (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 ¶m) {
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(例如在线程示例中(
- 不要使用命名空间std;这使得代码立即不可读。