The code below results in a crash of C++ on the line: free(arg). I am trying to prevent a memory leak from happening but i can't manage to free the data i stored in heap memory. Can someone help me with this problem?
Note that free(args) works fine.
#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;
}
Your both pointers respectively
args
andarg
are pointing to the same memory location and you are trying to release same memory location twice, and that creating the issue here. Please see below:-Just try like this for understanding, below example is not a solution but for your understanding. Here you assign
args = NULL
and that will be reflected inarg = NULL
henceif(arg != NULL)
will be false and hencefree(arg);
will not be call.:-