ReezaCoriza
ReezaCoriza

Reputation: 143

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

Upvotes: 0

Views: 3730

Answers (3)

Jens Gustedt
Jens Gustedt

Reputation: 78903

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

Upvotes: 2

Umer Farooq
Umer Farooq

Reputation: 7486

Add NULL character after each strncpy

lstring[left]='\0';


rstring[right]='\0';

Upvotes: 0

Barmar
Barmar

Reputation: 780984

The problem is that strncpy() doesn't add a null terminator if it stops because of the limit rather than reaching the end of the source string. So you need to add the null terminator.

int bit_count(char *passed, int len) {
    int left = len/2;
    int right = len - left;
    char *lstring = malloc(left+1);
    char *rstring = malloc(right+1);
    strncpy(lstring, passed, left);
    lstring[left] = '\0';
    strncpy(rstring, passed+left, right);
    rstring[right] = '\0';
    printf("Parent Left: %s\nParent Right: %s\n", lstring, rstring);
}

Upvotes: 2

Related Questions