释放c – loop中的子串
我正在尝试为结构’ structs
‘的每个成员获取一个子字符串,然后将该子字符串分配给temp_struct
的新成员。 我遇到的问题是如何在每次迭代时释放子字符串,由于某种原因代码运行,但是valgrind
抛出一个Invalid read of size 1
的Invalid read of size 1
,我假设我正在读取内存块。
我怎么能释放子串呢?
谢谢
#include #include #include struct st_ex { char product[16]; float price; }; struct st_temp { char *prod; }; char *temp = NULL; // from stackoverflow char* substr( const char* source, size_t start, size_t end ) { char* dest = malloc( end - start + 1) ; memcpy( dest, &source[start], end - start ) ; dest[end - start] = 0 ; return dest ; } int main() { struct st_ex structs[] = {{"mp3 player", 2.0f}, {"plasma tv", 20.0f}, {"notebook", 10.0f}, {"smartphone", 49.9f}, {"dvd player", 10.0f}, {"matches", 0.2f }}; struct st_temp **temp_struct; size_t j, i; temp_struct = malloc(sizeof *temp_struct * 6); for (j = 0; j < 6; j++) temp_struct[j] = malloc(sizeof *temp_struct[j]); size_t structs_len = sizeof(structs) / sizeof(struct st_ex); for(i=0; iprod = temp; free(temp); temp = NULL; } for(i=0; iprod); for(i=0; i<6; i++ ) free(temp_struct[i]); free(temp_struct); return 0; }
1)你正在释放子串
temp = substr(structs[i].product, 0, 4); temp_struct[i]->prod = temp; free(temp);
上面的第三行释放了你在substr
malloc的内存。
2)因为你在这里释放内存,你引入了一个bug。
释放后访问malloc内存是无效的,因此尝试打印temp_struct[i]->prod
无效。
解决方案?
不要free(temp)
,而是在你的循环中释放temp_struct[i]
,你首先需要释放temp_struct[i]->prod
,就像这样
for(i=0; i<6; i++ ) { free(temp_struct[i]->prod); free(temp_struct[i]); }
Josh,你的temp_struct
正在保持子字符串…你不想释放你当前正在释放它的子字符串。 无效的读取来自此行:
for(i=0; i<6; i++ ) printf("%s\n",temp_struct[i]->prod);
相反,你想在释放临时结构时释放子串,如下所示:
for(i=0; i<6; i++ ) { free(temp_struct[i]->prod); free(temp_struct[i]); }
不要释放子串。 在C中,子字符串是原始字符串的一部分。 如果要获取独立于字符串的子字符串,请使用strdup
。