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<unsignedchar> 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, (unsignedint) buffer.size());
delete enc_msg; // I added this...
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
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.