我有下面编写的代码,当调用时从内部数据库中提取值。数据库3rd colum包含BLOB格式的值。因此,对此数据库的调用是在开始和结束时间之间提取所有列。我正在使用malloc
unsigned char *valueBlobData = (unsigned char*)malloc(valueBlobSize);
为值bcoz保留内存一次可以有多个值。现在,如果我使用:
free(valueBlobData)
列表historyRows
不包含任何值。但是如果我没有freememory,那么我会在stl列表中收到值。但这会导致内存泄漏。
问题是,我是否在错误的位置释放记忆。如果是,我怎样才能使它发挥作用?
bool SQHISDB::getHisVArray(unsigned long startTime, unsigned long endTime,
std::list<tHistoryRow> &historyRows)
{
int rc;
int counter = 0;
tHistoryRow tempHistoryRow; // Struct having four variables
unsigned int A1 =1, A2=2;
const char *zSql = "SELECT * "
"FROM node_values "
"WHERE A1 = ? "
"AND A2 = ? "
"AND (sourceTS BETWEEN ? AND ? ) "
";";
sqlite3_stmt *pStmt = NULL;
rc = sqlite3_prepare_v2(this->db, zSql, std::strlen(zSql), &pStmt, NULL);
if (rc != SQLITE_OK)
{
return rc;
}
sqlite3_bind_int(pStmt, 1, A1);
sqlite3_bind_int(pStmt, 2, A2);
sqlite3_bind_int64(pStmt, 3, startTime);
sqlite3_bind_int64(pStmt, 4, endTime;
while (sqlite3_step(pStmt) == SQLITE_ROW)
{
counter++;
unsigned long sourceTimestamp = sqlite3_column_int64(pStmt, 4);
unsigned int valueBlobSize = sqlite3_column_bytes(pStmt, 3);
unsigned char *valueBlobData = (unsigned char*)malloc(valueBlobSize);
std::memcpy(valueBlobData, sqlite3_column_blob(pStmt, SQLITE_HISTORYDB_INDEX_VALUE), valueBlobSize);
tempHistoryRow.sourceTimestamp = sourceTS;
tempHistoryRow.blobSize = valueBlobSize;
tempHistoryRow.blob = valueBlobData;
historyRows.push_back(tempHistoryRow);
free(valueBlobData);
}
sqlite3_finalize(pStmt);
return true;
}
答案 0 :(得分:2)
实际上,你正试图将historyRows
推向悬空指针。这绝对是错误的。
对我而言,您似乎想使用简单的向量来管理此缓冲区。
struct tHistoryRow {
std::vector<unsigned char> blob;
… … …
};
bool SQHISDB::getHisVArray(unsigned long startTime, unsigned long endTime,
std::list<tHistoryRow> &historyRows)
{
int rc;
int counter = 0;
unsigned int A1 =1, A2=2;
static const std::string zSql{ "SELECT * "
"FROM node_values "
"WHERE A1 = ? "
"AND A2 = ? "
"AND (sourceTS BETWEEN ? AND ? ) "
";" };
sqlite3_stmt *pStmt = NULL;
rc = sqlite3_prepare_v2(this->db, zSql.data(), zSql.length(), &pStmt, NULL);
if (rc != SQLITE_OK)
{
return rc;
}
sqlite3_bind_int(pStmt, 1, A1);
sqlite3_bind_int(pStmt, 2, A2);
sqlite3_bind_int64(pStmt, 3, startTime);
sqlite3_bind_int64(pStmt, 4, endTime;
while (sqlite3_step(pStmt) == SQLITE_ROW)
{
counter++;
unsigned long sourceTimestamp = sqlite3_column_int64(pStmt, 4);
unsigned int valueBlobSize = sqlite3_column_bytes(pStmt, 3);
tHistoryRow tempHistoryRow; // it would be nice to provide constructor
tempHistoryRow.blob.resize(valueBlobSize);
auto pBlob = sqlite3_column_blob(pStmt, SQLITE_HISTORYDB_INDEX_VALUE);
std::copy(pBlob, pBlob + valueBlobSize, tempHistoryRow.blob.begin());
tempHistoryRow.sourceTimestamp = sourceTS;
historyRows.push_back(std::move(tempHistoryRow));
}
sqlite3_finalize(pStmt);
return true;
}
答案 1 :(得分:1)
释放内存并不意味着&#34; 清除&#34;内存,当你释放内存时,它只能用于其他分配,但是内存可能仍然包含与调用free之前相同的内容(或它的一些损坏版本,它取决于分配器的实现方式< / em>的)。
尝试检查(取消引用)已传递给free()
的指针是未定义的行为。