Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

0 bytes in 1 blocks are definitely lost in loss record 1 of 1

I’m learning C/C++ as a newcomer from java in school and since it is weekend, I can’t get help from there. I got an error like this:

==18== 0 bytes in 1 blocks are definitely lost in loss record 1 of 1
==18==    at 0x483C583: operator new[](unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==18==    by 0x109536: Table::Table(unsigned long) (taul2.cpp:38)
==18==    by 0x1093CF: main (taul2.cpp:108)

main:

  Table nums(7);
  nums.add(1); nums.add(2);
  cout << nums<< endl;
  Table nums2;
  taul.place(nums);
  cout << nums2<< endl;

  Table nums3;  // line 108
  cout << nums3 << endl;

  return 0;

Table:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Table{
    size_t max_size;
    size_t amount;
    int *numbers;
    int fail;
public:
Table(size_t size=0) 
{
    fail= 0;
    max_size = 0;
    numbers = new int[size]; // line 38
    if ( numbers ) max_size = size;
    lkm = 0;
}
  ~Table() { if ( max_size != 0 ) delete [] numbers; max_size = 0; }
/* ... */
}

The error only occurs on nums3 which length is 0, debugger shows that it goes to the ~Table method, just like all the others, but it is the only 1 with errors.

>Solution :

Even if you new 0 bytes, you still have to delete it. With every allocation, there’s a bit of additional overhead beyond the number of bytes you asked for. (e.g. entry in the heap, the pointer itself, etc…).

Side note: new items[0] does not return nullptr. And even if it did, delete [] nullptr is perfectly OK and safe.

Change your destructor from

~Table() { if ( max_size != 0 ) delete [] numbers; max_size = 0; }

To this:

~Table() { 
    delete [] numbers;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading