再次调用相同源的strncpy()失败 [英] strncpy() fails on second call for same source
问题描述
我是c的新手,想将字符串分为两部分。这是我的代码:
I'm new with c and want to separate string in two parts. Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void test(char** a, char** b)
{
const char * c = "abcdef";
*a = (char *)malloc(4* sizeof(char));
*b = (char *)malloc(4* sizeof(char));
strncpy(*a, c, 3);
*a[3] = '\0';
fprintf(stderr, "a -> %s\n", *a);
strncpy(*b, c+3, 3);
*b[3] = '\0';
fprintf(stderr, "b -> %s\n", *b);
}
int main()
{
setvbuf (stderr, NULL, _IONBF, 0);
char *a = NULL;
char *b = NULL;
test(&a, &b);
fprintf(stderr, "a -> %s\n", *a);
fprintf(stderr, "b -> %s\n", *b);
}
我想拥有 abc $ c $变量
a
和变量 b
中的 def
。但是我的问题是它失败并出现 Segmentation Fault
。运行此命令后,将得到以下输出:
I want to have abc
on a
variable and def
in variable b
. But my problem is that it fails with Segmentation Fault
. After I run this I get this output:
a -> abc
Segmentation fault
我不明白为什么。我正在使用 cygwin
并使用命令
I can't understand why. I'm using cygwin
and build it with command
gcc test.cpp -o进行构建test.exe
对不起,如果问题听起来很傻。谢谢。
Sorry if question sounds silly. Thank you.
推荐答案
array-subscript-operator []
有
The array-subscript-operator []
has higher precedence then the dereferencing operator *
.
所以您要更改
*a[3] = ...
成为
(*a)[3] = ...
与 b
相同。
已将编译器的警告级别设置得足够高,它应该已经对此发出警告。或至少告诉过您,它们是带有
Having set the compiler's warning level high enough, it should have warned you about this. Or at least told you that their is something fishy with
*a[3] = '\0';
这篇关于再次调用相同源的strncpy()失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!