小编Max*_*Max的帖子

结构体内部字符串的 malloc 溢出

以下代码是我目前正在处理的项目的示例,用 C 编码。

我首先 malloc 一个结构,然后作为例子 malloc 里面的第一个字符串。当我尝试将另一个字符串中的文本复制到其中并使用该printf函数打印它时,当我使用-fsanitize=addressas 编译标志进行编译时,它会溢出。

我不明白为什么,因为我认为我为字符串分配了足够的内存,因为我只是使用strlen另一个字符串的长度,为\0.

# include <stdio.h>
# include <stdlib.h>
# include <string.h>

typedef struct s_word
{
    int     length;
    char    *str;
}                       t_word;

typedef struct s_list
{
    t_word  *word;
}                       t_list;

int main(void)
{
    int     i;
    char    *line = "this is a test";
    t_list  test;

    i = -1;
    test.word = malloc(sizeof(t_word) * 10);
    test.word[0].str = malloc(sizeof(char) * (strlen(line) + 1));
    while (line[++i])
        test.word[0].str[i] = line[i];
    printf("%s\n", …
Run Code Online (Sandbox Code Playgroud)

c malloc struct address-sanitizer

1
推荐指数
1
解决办法
41
查看次数

标签 统计

address-sanitizer ×1

c ×1

malloc ×1

struct ×1