-1

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.

Tyler Shellberg
  • 1,086
  • 11
  • 28
  • 1
    You want `country` to have `malloc` `strlen(US_string) + 1` bytes so that you can properly [null terminate](https://en.wikipedia.org/wiki/Null-terminated_string) your string. – R_Kapp Feb 04 '16 at 18:26
  • 1
    http://stackoverflow.com/questions/17298172/how-does-sizeof-work-for-char-pointer-variables – Joseph Young Feb 04 '16 at 18:26
  • `man strncpy: [...]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.` – EOF Feb 04 '16 at 18:40

2 Answers2

1

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'

dlmeetei
  • 9,905
  • 3
  • 31
  • 38
  • EDIT: apparently you changed your comment, I'll look into the new one. – Tyler Shellberg Feb 04 '16 at 18:29
  • Appreciate the help! Appears to be working well now! However, I didn't null-terminate the string, and apparently it's still fine. I don't think I need to for what I'm using it for. Though If it starts giving me trouble I'll try it. Thanks! – Tyler Shellberg Feb 04 '16 at 18:52
1

sizeof will return the pointer size, not the string size. Use strlen +1 (to account for the 0 string termination char):

locations[0].country = malloc(strlen(US_string)+1);
sivann
  • 2,083
  • 4
  • 29
  • 44