gpt4 book ai didi

c - 返回动态分配的副本 const char *s,而不使用标准库中除 malloc() 和 free() 之外的任何其他函数

转载 作者:行者123 更新时间:2023-11-30 16:35:24 25 4
gpt4 key购买 nike

我正在尝试编写一个名为 strdup 的函数,其中 strdup() 返回 s 的动态分配副本,或在失败时返回 NULL。 s 是一个 C 字符串。这返回的副本还必须是有效的 C 字符串,使用副本所需的最小存储量。

除了 malloc() 和 free() 之外,我不允许使用任何其他函数(例如,来自标准库或其他假设的函数)。我可能会假设,如果我返回动态分配存储的地址,则用户有责任释放该存储。

这是我想到的。

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

char *strdup(const char *s)
{
char *copy;
unsigned length = 0; //best to use here, given the cirumstance

while(s[length] != '\0')
{
++length;
}
++length;

copy = malloc(sizeof(*copy) * length); //better to use the size of copy

if(copy == 0)
{
return 0;
}

char *copy_orig = copy; //save a copy of 'copy', but why?

while(*s) //testing for a null char, not a null pointer (while(s))
{
*copy++ = *s++; //seg fault
}
*copy = '\0';

return copy_orig;//why?
}

int main(int argc, char* argv[])
{
const char *s = "Hello, I am a String";
printf("%s\n", s);

printf("%s", strdup(s));
}

代码可以编译,但在运行时出现段错误,我不知道为什么。

最佳答案

在 while 循环中,您不会增加指针。我将其重写为不使用指针进行复制

char *strdups(const char *s1)
{
int i;
int lenth;
char *p;

lenth = 0;
while (s1[lenth])
lenth++;

if ((p = malloc(sizeof(char) * (lenth + 1))) == NULL);
return NULL;

i = 0;
while (s1[i])
{
p[i] = s1[i];
i++;
}
p[i] = '\0';
return p;
}

如果你想使用指针来编写它

char *strdups(const char *s1)
{
int len;
char *p;
char *tmp;

len = 0;
while (s1[len])
len++;

if ((p = malloc(sizeof(char) * (len + 1))) == NULL)
return NULL;

tmp = p;
while (*tmp++ = *s1++);
/* Empty Body */

*tmp = '\0';
return p;
}

关于c - 返回动态分配的副本 const char *s,而不使用标准库中除 malloc() 和 free() 之外的任何其他函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48937398/

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