Search code examples
cmallocstrncpy

Malloc and strncpy


I am trying to split a string in two to pass to two children. the first part should be 12 '0' characters and the second should be 13 '1' characters. When I execute this code, I do not get either of these things. specifically this is the output. Parent Left: 00000000000 Parent Right: 0000000000001 I have no idea why, can someone help?

int bit_count(char *passed, int len){
int left = len/2;
int right =(len/2)+(len % 2);
char *lstring = malloc(sizeof(char)*(left+1));
char *rstring = malloc(sizeof(char)*(right+1));
strncpy(lstring, passed, sizeof(char)*12);
strncpy(rstring, passed+left, sizeof(char)*13);
printf("Parent Left: %s\n", lstring);
printf("Parent Right: %s\n", rstring);

Solution

  • Don't use strncpy if you don't need it and if you don't know exactly what it does.

    In your case it is completely superfluous, you know the size of the array that you want to copy, anyhow. So use memcpy:

    memcpy(lstring, passed, left);
    lstring[left] = '\0';
    memcpy(rstring, passed+left, right);
    rstring[right] = '\0';