Search code examples
cstringmallocstrlenstrncpy

Why does the string I copied using strncpy have junk instead of the last character?


I malloc'd an array of structures called "locations". In said structure is an element called "country". I created a string you can see below that holds "United States" in it. I malloc'd space to hold the string (it's required that I do so) and attempted to use strncpy to place the string into the malloced space.

This works elsewhere in my code with strings that are read in from a file, but not for this string which I declared directly.

When I print out the result, it says the structure is holding "United State(error symbol)"

So in place of the s at the end of "United States" is the error symbol.

The error symbol looks like a small box of ones and zeros.

char *US_string = "United States";
locations[0].country = malloc(sizeof(US_string));
strncpy(locations[0].country, US_string, strlen(US_string));

Anyone know what's going on?

Thanks for any help! And please try not to be too hard on me, I'm a first year CS major. Just trying to get this bug out of a lab.


Solution

  • mallocing need to be adjusted by adding 1to account for '\0'. Moreover sizeof(US_string) will give size of pointer, which may be different from actual string size. Hence

    locations[0].country = malloc(strlen(US_string) + 1);
    

    and missing locations[0].country[strlen(US_string)] = '\0'