gpt4 book ai didi

c - 段错误(核心转储)- strlcpy 函数 C

转载 作者:行者123 更新时间:2023-12-04 09:04:21 26 4
gpt4 key购买 nike

我一直在构建一些基本的 C 函数,但我仍然没有太多经验。
编码时 strlcpy 功能我不断收到 段错误(核心转储)错误。认为它可能与 NUL 终止字符串有关,但我在运行时不断收到错误消息。
任何帮助将不胜感激,提前致谢。

#include <string.h>
#include <stdio.h>
#include <bsd/string.h>

unsigned int ft_strlcpy(char *dst, char *src, unsigned int size)
{
unsigned int i;
unsigned int j;

j = 0;
while (src[j] != '\0')
j++;

if (size == 0)
return (j);

i = 0;
while (i < (size - 1) && src[i] != '\0')
{
dst[i] = src[i];
i++;
}
dst[i] = '\0';
return (j);
}

int main()
{
char *str;

str = "byes";
str[3] = '\0';
printf("%s", str);
printf("%u", ft_strlcpy("hello", str, 5));
return (0);
}
更正功能以防有人需要它
unsigned int    ft_strlcpy(char *dst, char *src, unsigned int size)
{
unsigned int i;
unsigned int j;

j = 0;
while (src[j] != '\0')
j++;

if (size == 0)
return (j);

i = 0;
while (i < (size - 1) && src[i] != '\0')
{
dst[i] = src[i];
i++;
}
dst[i] = '\0';
return (j);
}

int main()
{
char str[] = "byes";
char dest[] = "hello";

printf("%s\n", str);
printf("%u\n", ft_strlcpy(dest, str, 5));
printf("%s\n", dest);

return (0);
}
那应该返回:
byes
4
byes

最佳答案

您声明了一个指向字符串文字的指针

char *str;

str = "byes";
字符串文字不得更改。但是您正在尝试更改指向的字符串文字
str[3] = '\0';
这会导致未定义的行为。
删除此声明。字符串文字已经在索引等于 4 处包含终止零。
也在这个电话中
printf("%u", ft_strlcpy("hello", str, 5));
您再次尝试使用函数 ft_strlcpy 更改字符串文字.在这种情况下,它是字符串文字 "hello" .
例如声明一个字符数组
char dsn[] = "hello";
并将其作为参数传递给函数
printf("%u", ft_strlcpy( dsn, str, sizeof( dsn )));

关于c - 段错误(核心转储)- strlcpy 函数 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63487353/

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