Home > database >  C Error when deleting a node not working after updating mac
C Error when deleting a node not working after updating mac

Time:10-21

I am using Vscode on macOS and I am facing this error when deleting

tests(2715,0x102460580) malloc: *** error for object 0x150e06930: pointer being freed was not allocated
tests(2715,0x102460580) malloc: *** set a breakpoint in malloc_error_break to debug

This happens when I try deleting a node that I dynamically allocated. It was working fine up until when I updated my Mac version and reinstalled the Xcode command line tools.

CodePudding user response:

Most probably your program had a memory allocation bug even before the update. It's possible but unlinkely that the macOS update is buggy.

In addition to the examples in @metal's answer, here is another buggy example:

int main() {
  char *buf = new char[4096];
  char *p = buf   1;  // No bug below without the   1 here.
  delete [] p;  // This line is buggy.
  return 0;
}

It is buggy because all pointers passed to delete must be returned by new.

In real code usually the ... and the delete are in different functions, so the bug is not obvious by first look.

CodePudding user response:

Can you post a minimum sample that demonstrates the problem?

Is it that you're mixing new/delete allocating with malloc/free allocating, like:

#include <cstdlib>

int main()
{
  int* pi = (int*)std::malloc(sizeof(int));
  delete pi;

  // OR
  int* pi2 = new int();
  std::free(pi2);

}

Or that you're de-allocating something that actually lives on the stack:

int main()
{
  int i = 42; // on the stack
  std::free(&i);
}

PS, generally speaking in C , standard containers like std::vector and helpers like std::make_unique() are preferred over naked new/delete, which themselves are preferred over malloc/free, which are the old school C functions. For more info, see these FAQs:

  • Related