c - 我想直接创建 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));
}
解决方案
你的实现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;
}
推荐阅读
- if-statement - if....if 块和 if....else 块的流程之间的区别
- r - 将数据框中的行、列和值转换为 R 中的 3 个不同的列
- webrtc - 我应该在添加我方的 localMedia 曲目之前发送 WebRTC 答案吗?
- firebase - Adjust 和 Firebase 之间的收入差异
- arrays - 我想知道为什么下面的这个程序不起作用我想打印每个字符串的反面?
- c# - 放大 Windows API - 如何添加平滑/抗锯齿
- typescript - 在 VsCode 中使用附加的调试器进行调试时在 Typescript 文件上命中断点
- android - 在场景中动态改变模型纹理
- python - SQLAlchemy MySQL 连接挂起
- java - 有没有办法压缩变量赋值?