我已经建立了一些基本的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);
}
发布于 2020-08-19 12:59:59
您声明了指向字符串文本的指针。
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 )));
https://stackoverflow.com/questions/63487353
复制相似问题