c - 在 C 循环中释放子字符串

标签 c struct free malloc substring

我正在尝试为结构“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/

相关文章:

c - strtol 使用 errno

c - 重复的 udp 数据包 : how often it happens?

c - 无符号 96 位整数的任何预定义类型?

c - 结构并将值传递给它们

c - 运行时检查失败 #2 - 变量 'd' 周围的堆栈已损坏

ARM 中基于堆栈的结构的调用约定?

c - 另一个结构中的结构的图形解释,但指向它的指针,

C 内存错误调试断言失败

释放内存的正确方法

c - C 代码中的 SIGBART 与 malloc/free