gpt4 book ai didi

c - 关于动态分配内存给 char 指针的简单问题

转载 作者:行者123 更新时间:2023-12-04 11:33:14 29 4
gpt4 key购买 nike

我正在准备数据结构和算法考试。与动态内存分配相关的示例问题之一要求您创建一个传递字符串的函数,该函数将其复制到用户定义的字符指针。该问题提供了开始的结构体。我做了这样的事情:

typedef struct smart_string {
char *word;
int length;
} smart_string;

smart_string* create_smart_string(char *str)
{
smart_string *s = (smart_string*)malloc(sizeof(smart_string));
s->length = strlen(str);
s->word = malloc(s->length);
strcpy(s->word, str);
return s;
}

但答案是这样的

typedef struct smart_string {
char *word;
int length;
} smart_string;

smart_string *create_smart_string(char *str)
{
smart_string *s = malloc(sizeof(smart_string));
s->length = strlen(str);
s->word = malloc(sizeof(char) * (s->length + 1));
strcpy(s->word, str);
return s;
}

我继续使用 code:blocks 并测试它们以查看任何主要差异。据我所知,它们的输出是相同的。

我按照现在的方式编写代码,因为我想如果我们要为 s->word 分配一个特定的内存块,那么它应该与 的字节数相同s ->length,因为这是我们要复制的字符串。

然而,下面的正确答案是将 sizeof(char)(只有 1 个字节)乘以 s->length + 1。为什么需要将 1 添加到 s->lengths->length 乘以 sizeof(char) 有何重要性?我在回答中犯了哪些错误需要注意?

最佳答案

sizeof(char) == 1 根据定义,所以这无关紧要。

你不应该转换 malloc 的结果:Do I cast the result of malloc?

你唯一真正的区别是 strlen 返回字符串的长度,不包括终止 NUL ('\0') 字符,所以你需要添加+ 1 到解决方案中的缓冲区大小。

如果你在那里复制字符串,终止字符不会被复制(或者更糟的是,它会被复制到其他内存),因此,任何处理字符串的函数(除非你使用特殊的安全函数,例如strscpy) 将遍历缓冲区并越过它,因为它们找不到结尾。那时它是未定义的行为,一切都可能发生,甚至按预期工作,但不能依赖它。

它按预期工作的原因是因为缓冲区旁边的内存可能为 0,因此它被解释为终止字符。

关于c - 关于动态分配内存给 char 指针的简单问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56120859/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com