Two errors:
C language allows the creation of arrays on the stack of variable length, but C ++ does not. In C ++ the size of the arrays allocated in the stack must be known at compile time.
You are giving delete
to free memory from an array allocated on the stack. This is neither permitted nor necessary. Objects created on the stack are destroyed automatically at the end of the scope that declared them.
If the array has a fixed size, set at compile time, it is not necessary to give delete[]
in it.
If your size is variable then you will need to do dynamic allocation. Some options:
Manual management:
char *fileName = new char[size];
memset(fileName,'\n',size);
sprintf(fileName, "%s/%s%s-%05u.%s", filePath.c_str(), filePrefix.c_str(), date, this->image_counter++, fileExtension.c_str());
cv::imwrite(fileName, frame);
delete[] fileName;
Automatic management with unique_ptr
:
std::unique_ptr<char[]> fileName(new char[size]);
memset(fileName.get(),'\n',size);
sprintf(fileName.get(), "%s/%s%s-%05u.%s", filePath.c_str(), filePrefix.c_str(), date, this->image_counter++, fileExtension.c_str());
cv::imwrite(fileName.get(), frame);
//Não é necessário dar delete, quando o unique_ptr sair de escopo ele liberará a memória
The two tests generate exactly the same assembly, as can be seen here in a simplified example: link . There is no loss of performance by using std::unique_ptr
.
Another option is with std::vector
:
std::vector<char> fileName(size, '\n');//Cria um vector de tamanho size, preenchido com \n
sprintf(fileName.data(), "%s/%s%s-%05u.%s", filePath.c_str(), filePrefix.c_str(), date, this->image_counter++, fileExtension.c_str());
cv::imwrite(fileName.data(), frame);
//Não é necessário dar delete, quando o vector sair de escopo ele liberará a memória
But in this case the code generated is a little lower.