Malloc后的自由功能错误
Error with free function after malloc
以下代码在行上导致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;这使得代码立即不可读。
相关文章:
- Malloc后的自由功能错误
- 功能错误中的表达语法帮助!C/C
- 将对象传递到类,没有接收匹配功能错误
- 无效打印功能错误
- 绑定std ::功能错误
- 我可以启用有关我自己的变异功能错误使用的指定符的警告
- 功能错误的使用无效
- C 朋友模板功能错误
- 单链接列表推送功能错误
- ConstexPR静态模板功能:G 错误是Clang上的警告
- 一个奇怪的打印功能错误
- 信号功能错误
- 查找最低值.功能.错误:线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x7fff5fc89000)
- 超载功能错误消息
- 与操作员'<<'不匹配 有人可以帮助解决无效功能错误吗?[C++]
- 没有操作员发现升压read_xml功能错误
- 工厂设计模式中的纯虚拟功能错误
- 如何跟踪LLVM验证功能错误"Expected no forward declarations!"?
- OOP项目功能错误
- c++ GTK控制台日志功能错误