分段故障核心已转储-strlcpy函数C

问题描述

我一直在构建一些基本的C函数,但是我还是不太有经验。

在对 strlcpy 函数进行编码时,我不断收到分段错误(内核已转储)错误。以为它可能与NUL终止的字符串有关,但是我在运行时不断收到错误消息。

任何帮助,请先感谢。

FileWriter(path,true)

在有人需要的情况下纠正功能

#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,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,5));
    printf("%s\n",dest);

    return (0);
}

解决方法

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

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,sizeof( dsn )));

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...