我正在尝试为结构“structs
”的每个成员获取一个子字符串,然后将该子字符串分配给 temp_struct
的新成员.
我遇到的问题是如何在每次迭代时释放子字符串,出于某种原因代码运行,但是 valgrind
抛出 Invalid read of size 1
,这我假设我正在读取内存块。
如何释放子字符串?
谢谢
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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; i<structs_len; i++){
temp = substr(structs[i].product, 0, 4);
temp_struct[i]->prod = temp;
free(temp);
temp = NULL;
}
for(i=0; i<6; i++ )
printf("%s\n",temp_struct[i]->prod);
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) 因为你在这里释放了内存,所以你引入了一个错误。
释放后访问 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]);
}
关于c - 在 C 循环中释放子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3187445/