C:释放每个 malloc 还是仅释放主要的?
我有一个指针 ***resultSet,我将其作为参数传递给 SQL 函数,该函数从数据库读取未知数量的数据。数据的实际处理发生在函数之外。
当清理这个指针构造时,我是否只释放主指针一次并释放所有后续分配,或者我是否必须释放我创建的每个 malloc?
while((row = mysql_fetch_row(result))) {
// allocating the rows pointer
resultSet = malloc(sizeof(void)*(int)mysql_num_rows);
(*rows)++;
for (i=0 ; i < mysql_num_fields(result); i++)
{
// allocating the fields pointer
*(resultSet+i) = malloc(sizeof(void)*(int)mysql_num_fields);
// allocating the character pointer
**resultSet = malloc(sizeof(char)*strlen(row[i])+1);
(*fields)++;
snprintf(**resultSet, strlen(row[i])+1, "%s", row[i]);
printf("%s\t",**resultSet);
if (i==6)
{
printf("\t %s\n",**resultSet);
}
}
}
I have a pointer ***resultSet that I pass as parameter to my SQL function which reads an unknown amount of data from the DB. The actual handling of the data happens outside the function.
When cleaning up this pointer construct, do I just free the main pointer once and free finds all the subsequent allocations or do I have to free up every malloc I created?
while((row = mysql_fetch_row(result))) {
// allocating the rows pointer
resultSet = malloc(sizeof(void)*(int)mysql_num_rows);
(*rows)++;
for (i=0 ; i < mysql_num_fields(result); i++)
{
// allocating the fields pointer
*(resultSet+i) = malloc(sizeof(void)*(int)mysql_num_fields);
// allocating the character pointer
**resultSet = malloc(sizeof(char)*strlen(row[i])+1);
(*fields)++;
snprintf(**resultSet, strlen(row[i])+1, "%s", row[i]);
printf("%s\t",**resultSet);
if (i==6)
{
printf("\t %s\n",**resultSet);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
作为一般规则,对于每个
malloc()
都有一个free()
。As a general rule, for every
malloc()
you have afree()
.它的作用正如它所说的那样——释放指向的内存。它不查看内存中存储的内容;而是查看内存中存储的内容。它不知道任何其他分配的内存。它只是释放你告诉它的东西。因此,正如其他人所说,如果您想释放分配的所有内存,则必须
释放
所有malloc
的内容。(也许您正在考虑 C++ 更复杂的行为,当您销毁一个对象时,它的成员也会被销毁?)
It does exactly what it says - frees the memory pointed to. It doesn't look at what's stored in that memory; it has no idea about any other allocated memory. It just frees what you tell it to. So, as others have said, if you want to free all the memory you allocated, you have to
free
everything youmalloc
ed.(Perhaps you were thinking of the more sophisticated behavior of C++, where when you destroy an object, its members are also destroyed?)
您必须为您声明的每个
malloc()
调用free()
以防止内存泄漏。you have to call
free()
for everymalloc()
you stated to prevent a memory leak.您基本上需要反向工作并释放每个分配。
You will need to basically work in reverse and free each allocation.