作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我一直在构建一些基本的 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';
这会导致未定义的行为。
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/
我正在为我的应用程序使用 Tank-Auth。我唯一的问题是激活和重置帐户密码。 用于登录、注册、注销;我对这些代码没有问题; $route['login'] = "/auth/login"; $ro
我是一名优秀的程序员,十分优秀!