strncpy() fails on second call for same source

爷,独闯天下 提交于 2020-01-11 13:22:47

问题


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);
}

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

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.


回答1:


The array-subscript-operator [] has higher precedence then the dereferencing operator *.

So you want to change

*a[3] = ...

to be

(*a)[3] = ...

Same for 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';


来源:https://stackoverflow.com/questions/46620060/strncpy-fails-on-second-call-for-same-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!