cstringmallocstrncpy

Weird behavior with stack and heap while using strncpy


I found a very interesting question.

When I'm using following code:

int main() {
    char * in = "hi, ";
    char str[10];
    strncpy(str, in, 2);
    printf("output = %s", str);
    return 0;
}

My result is nothing, the printf didn't work.

But if I use this:

int main() {
    char * in = "hi, ";
    char * str = malloc(sizeof(char) * 10) ;
    strncpy(str, in, 2);
    printf("output = %s", str);
    return 0;
}

I can get what I expect.

Why does this happen? Is it because of stack and heap? How exactly does that makes this huge difference?


Solution

  • The code compiles fine. The run-time error could be because, you haven't terminated the str with null.

    From the man page:

    The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null terminated.

    Add str[2]=0; after the strncpy().