首页 > 解决方案 > 我想直接创建 strncpy 函数,你能查看我的代码吗?有总线错误

问题描述

我想strncpy通过代码实现功能,而不是使用库或标题

但是有zsh总线错误.....我的代码有什么问题?zsh总线错误是什么?

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

char    *ft_strncpy(char *dest, char *src, unsigned int n)
{
    unsigned int    i;

    i = 0;
    while (i < n && src[i])
    {
        dest[i] = src[i];
        i++;
    }
    while (i < n)
    {
        dest[i] = '\0';
        i++;
    }
    return (dest);
}

int main()
{
    char         *A = "This is a destination sentence";
    char         *B = "abcd";
    unsigned int  n = 3;

    printf("%s", ft_strncpy(A, B, n));
}

标签: cbusstrncpy

解决方案


你的实现strncpy很好,容易出错的函数的不可思议的语义得到了正确的实现(除了类型之外n,应该是size_t)。

您的测试函数不正确:您将字符串常量的地址作为目标数组传递,ft_strncpy()尝试写入时会导致未定义的行为。不得写入字符串常量。如果可用,编译器可能会将它们放在只读存储器中。在您的系统上,写入只读内存会导致总线错误,正如 shell 报告的那样。

这是一个以本地数组为目标的修改版本:

int main()
{
    char          A[] = "This is a destination sentence";
    const char   *B = "abcd";
    unsigned int  n = 3;

    printf("%s\n", ft_strncpy(A, B, n));
    return 0;
}

推荐阅读