What if, memory allocated using malloc is deleted using delete rather than free

Viewed 11432

I came across an issue which I could not resolve.

My question is, if I used malloc to allocate memory and then memory block is delete using delete? The general thumb rule is

If we allocate memory using malloc, it should be deleted using free.

If we allocate memory using new, it should be deleted using delete.

Now, in order to check what happens if we do the reverse, I wrote a small code.

#include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;

class A
{
  int p=10;
public:
  int lol() {
    return p;
  }
};

int main()
{
  int *a = (int *)malloc(sizeof(int)*5);
  for(int i=0; i<4; i++) {
    a[i] = i;
    cout << a[i] << endl;
  }

  delete(a);
  // Works fine till here..

  A b;
  cout << b.lol() << endl;
  free(b); // Causes error.     

  return 0;
}

The error which I get is:

error: cannot convert ‘A’ to ‘void*’ for argument ‘1’ to ‘void free(void*)’

I am unable to understand why is this happening. Please explain.

8 Answers

free() accepts a pointer. You are passing an object (not a pointe) to free. That is why you are getting the error. If you make below change, your code works fine.

A *a = new A;
free(a);

Though the code above works fine, it will lead to a memory leak because free() doesn't call the destructor, which is responsible for freeing the resource(s) created by the constructor.

Related