简体   繁体   中英

strncpy() fails on second call for same source

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM