Search code examples
c++mallocfreebeginthread

Error with free function after malloc


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;
}

Solution

  • Your both pointers respectively args and arg 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:-

     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
    

    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 in arg = NULL hence if(arg != NULL) will be false and hence free(arg); will not be call.:-

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