I have a struct which contains a set of char* properties.
struct gcp_values {
char* srcX;
char* srcY;
char* dstX;
char* dstY;
};
well I fill it in a loop from a set of qt objects
std::vector<GeoRefLibrary::gcp_values> gcpvalues(vl.size());
for(int i=0;i<vl.size();i++) {
gcppoint_ *a = qobject_cast<gcppoint_ *>(vl.at(i).value<QObject *>());
gcpvalues[i].srcX= strdup(QString::number(a->row()).toStdString().c_str());
gcpvalues[i].srcY= strdup(QString::number(a->column()).toStdString().c_str());
gcpvalues[i].dstX= strdup(QString::number(a->lon()).toStdString().c_str());
gcpvalues[i].dstY= strdup(QString::number(a->lat()).toStdString().c_str());
}
when I run valgrind test it results these outpt
12 bytes in 4 blocks are definitely lost in loss record 813 of 19,623
14 bytes in 4 blocks are definitely lost in loss record 889 of 19,623
16 bytes in 1 blocks are definitely lost in loss record 3,621 of 19,623
32 bytes in 4 blocks are definitely lost in loss record 8,851 of 19,623
36 bytes in 4 blocks are definitely lost in loss record 9,134 of 19,623
these errors are at those lines in loop. I tried to delete [] gcpvalues
but it returned wrong delete/free error. I searched and found this post too
but cant find the solutions,can some one please help me with this problem?
I also tried
struct gcp_values {
QString srcX;
QString srcY;
QString dstX;
QString dstY;
};
and it returns the same errors
I changed the loop into this and it seems errors are gone
for(int i=0;i<vl.size();i++) {
gcppoint_ *a = qobject_cast<gcppoint_ *>(vl.at(i).value<QObject *>());
char* srcX = strdup(QString::number(a->row()).toStdString().c_str());
char* srcY = strdup(QString::number(a->column()).toStdString().c_str());
char* dstX = strdup(QString::number(a->lon()).toStdString().c_str());
char* dstY = strdup(QString::number(a->lat()).toStdString().c_str());
gcpvalues[i].srcX=srcX;
gcpvalues[i].srcY= srcY;
gcpvalues[i].dstX= dstX;
gcpvalues[i].dstY= dstY;
if(srcX) { free(srcX);}
if(srcY) { free(srcY);}
if(dstX) { free(dstX);}
if(dstY) { free(dstY);}
}
strdup
is a POSIX function, and POSIX functions which allocate memory (and do not provide type-specific deallocation functions such as fclose
and freeaddrinfo
) expect the caller to eventually call free
to deallocate the allocated memory.
POSIX does not use C++ memory allocation, so operator delete[]
is not correct here.