views:

46

answers:

2

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.

A: 

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.

DeadMG
+5  A: 

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.

Steve Jessop
@Steve Jessop: Thanks I understand now!
Tommy