user2336315
user2336315

Reputation: 16067

Displaying output with strncopy

I begin with C and I have to write a method that returns each word in a sentence separated by a whitespace.

So far I have this:

#include<stdio.h>
#include<string.h>

#define SIZE 100

int nextToken(char const * str, int* from, int* len);

int main(){
    char str[SIZE+1];
    char mot[SIZE+1];

    if(fgets(str, SIZE, stdin) == NULL){
        puts("Error");
        return -1;
    }
    str[SIZE] = '\0';

    int from = 0;
    int len = 0;

    while(nextToken(str, &from, &len)){
        strncpy(mot, &(str[from]), len);
        mot[SIZE] = '\0';
        printf("'%s'\n", mot);
        return 0;
    }
    return 0;
}

int nextToken(char const * str, int* from, int* len){
    *from = 1;
    *len = 2;
    return 1;
}

I know the return 0 in the while but it's just to run it one time.

So in the nextToken function, when changing the value pointed by len to 1, I get the expected output for the input hello, i.e 'e'.

But when changing the value pointed by len to 2, I was expecting to get 'el' but I get 'el¿■('.

Why do I have this output, why it doesn't print 'el'?

Sorry if it's stupid but I don't know why this is happening as I begin. I'm compiling in C89.

Upvotes: 0

Views: 83

Answers (1)

David Heffernan
David Heffernan

Reputation: 612914

strncpy does not copy a null-terminator in case it copies len characters. In that eventuality you need to ensure that the string is null-terminated explicitly.

Frankly, I don't think that strncpy is really the right function for you to use here.

I'd write it like this:

memcpy(mot, str+from, len);
mot[len] = '\0';

And you'd want to include a check that this did not result in a buffer overrun.

Upvotes: 2

Related Questions