Reputation: 34533
char* temp;
temp = (char*) malloc (strlen(window->entry.value)+1);
//strncpy( temp, window->entry.value, sizeof(temp) ); DOESN"T WORK
memcpy (temp, window->entry.value, strlen(window->entry.value) + 1); //WORKS
(where window->entry.value is a string.)
Thanks.
Upvotes: 2
Views: 1451
Reputation: 279255
sizeof(temp)
doesn't do what you think it does. It tells you the size, in bytes, of a pointer to char, which is what temp
is. Most likely on your system either 4 or 8.
This has nothing to do with the length of any particular string, or the size of any particular buffer returned from malloc
.
It's pure fluke that you've passed the right length when using memcpy
, and the wrong length when using strncpy
. memcpy
would also not work if passed sizeof(temp)
as the length, and strncpy
would work if passed the right length.
Upvotes: 6
Reputation: 146930
Strncpy doesn't care where you get your memory. The fact that you used sizeof(temp) shows that you don't know left from right in C strings, because that only works for statically allocated char[] buffers. The reason that memcpy works and strncpy doesn't is because you actually passed a sensible length parameter to memcpy but totally forgot to make this parameter make any sense to strncpy.
Upvotes: 0