3
    unsigned char *bin_data;
    unsigned char *bin_model;

    bin_data = new unsigned char[200];
    memset(bin_data, 0, 200);
    bin_model = new unsigned char[200];
    memset(bin_model, 0, 200);

I was reviewing the code above and I have a gut feel that it might cause a memory leak, but I logically cannot find the reason.

I am thinking it is because we have memset a pointer to 0, the address of the data might be lost. What we wanted to do was just to initialize bin_data and bin_model before acquiring data from an interface which will be used in further processing, since acquiring the data has a chance to fail.

Will the code above cause any problems?

Thanks!

Wolf
  • 91
  • 1
  • 7

4 Answers4

6
memset(bin_data, 0, 200);

...writes 200 zeros starting at the address pointed by bin_data. memset doesn't overwrite the pointer itself to zero. The address is kept intact.

If there is a memory leak in this code it would be due to a lack of delete[].

cfillion
  • 1,340
  • 11
  • 16
1

Yes, you need to delete the allocated memory to prevent memory leak:

delete[] bin_data;
delete[] bin_model;

But it's not recommended to use raw new and delete, a better solution is to use a vector, it also initializes the data to zero:

std::vector<unsigned char> bin_data(200);

If you need a non-const pointer to the data, you can use a unique_ptr or shared_ptr which automatically frees the memory.

C++11:

auto bin_data = std::unique_ptr<unsigned char[]>(new unsigned char[200]);

C++14:

auto bin_data = std::make_uniue<unsigned char[]>(200);

And you can get the underlying pointer with bin_data.get()

krisz
  • 2,686
  • 2
  • 11
  • 18
  • Thanks @krisz. I was planning to suggest unique pointers to improve the codes above too. :) – Wolf Jun 18 '18 at 02:31
1

I am thinking it is because we have memset a pointer to 0, the address of the data might be lost.

memset takes an address as the first value. The pointer you passed points to a location in the heap. The pointer itself is stored on the stack. The buffer pointed to is overwritten, the pointer is untouched.

Since you tagged this "C++" you should really heed the advice in the other answers: smart pointers are the way to go, don't use naked pointers for heap allocations like these.

Brian Cain
  • 14,403
  • 3
  • 50
  • 88
0

I think you would have problems if you did not clear your memory you added on the heap (using the keyword delete) or left a dangling pointer.