Trying to understand the use of "new" in this code

I got the snippet of code below at Stack Overflow, I rarely use the 'new' keyword and trying to understand why it was used in this case, and if there are better ways.

I read "every time you type new, type delete". So I'm guessing once I'm done with *enc_msg, I delete it. By the way, this snippet is being called within an infinite while loop.

1
2
3
4
5
6
7
8
std::vector<unsigned char> buffer; // changed from uchar to unsigned char
cv::imencode(".jpg", frame1, buffer, compression_params);
uchar *enc_msg = new uchar[buffer.size()]; // Not sure about this...
for (int i = 0; i < buffer.size(); i += 1) {
	enc_msg[i] = buffer[i];
}
std::string codebase64 = base64_encode(enc_msg, (unsigned int) buffer.size());
delete enc_msg; // I added this... 
Last edited on
Your use of delete is almost correct. After a new [] you need delete[].
Hence line 8 should be
 
delete [] enc_msg;


However, not sure you need any of that when using vectors and std::string, each of those can handle dynamic memory allocation without the use of new/delete

Maybe this would work - I'm unable to test it:
1
2
3
std::vector<unsigned char> buffer;
cv::imencode(".jpg", frame1, buffer, compression_params);
std::string codebase64 = base64_encode(buffer.data(), buffer.size());
If you have new ... [] you need to call delete[]

Within that snippet the whole enc_msg does not make sense.
Chevril thanks for explaining the first solution, and I definitely tested your second solution and it worked perfectly. I just had to cast buffer.size() to unsigned int otherwise I get an annoying conversion warning.

coder777 you're right, thankfully Chevril pointed that out. I updated the code.

1
2
3
4
// This worked, thanks.
std::vector<unsigned char> buffer;
cv::imencode(".jpg", frame1, buffer, compression_params);
std::string codebase64 = base64_encode(buffer.data(), (unsigned int) buffer.size());
Last edited on
Topic archived. No new replies allowed.