以下代码是我目前正在处理的项目的示例,用 C 编码。
我首先 malloc 一个结构,然后作为例子 malloc 里面的第一个字符串。当我尝试将另一个字符串中的文本复制到其中并使用该printf
函数打印它时,当我使用-fsanitize=address
as 编译标志进行编译时,它会溢出。
我不明白为什么,因为我认为我为字符串分配了足够的内存,因为我只是使用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)