strcpy()/strncpy() crashes on structure member with extra space when optimization is turned on on Unix?

What you are doing is undefined behavior. The compiler is allowed to assume that you will never use more than sizeof int64_t for the variable member int64_t c. So if you try to write more than sizeof int64_t(aka sizeof c) on c, you will have an out-of-bounds problem in your code. This is the case … Read more

C – why is strcpy() necessary

Arrays in C are non-assignable and non-copy-initializable. That’s just how arrays are in C. Historically, in value context (on the RHS of assignment) arrays decay to pointers, which is what formally prevents assignment and copy-initialization. This applies to all arrays, not only to char arrays. C language inherits this arrays behavior from its predecessors – … Read more

strcpy() return value

as Evan pointed out, it is possible to do something like char* s = strcpy(malloc(10), “test”); e.g. assign malloc()ed memory a value, without using helper variable. (this example isn’t the best one, it will crash on out of memory conditions, but the idea is obvious)

Does C have a string type? [closed]

C does not and never has had a native string type. By convention, the language uses arrays of char terminated with a null char, i.e., with ‘\0′. Functions and macros in the language’s standard libraries provide support for the null-terminated character arrays, e.g., strlen iterates over an array of char until it encounters a ‘\0’ … Read more

Proper way to empty a C-String

It depends on what you mean by “empty”. If you just want a zero-length string, then your example will work. This will also work: buffer[0] = ‘\0’; If you want to zero the entire contents of the string, you can do it this way: memset(buffer,0,strlen(buffer)); but this will only work for zeroing up to the … Read more

strcpy vs strdup

strcpy(ptr2, ptr1) is equivalent to while(*ptr2++ = *ptr1++) where as strdup is equivalent to ptr2 = malloc(strlen(ptr1)+1); strcpy(ptr2,ptr1); (memcpy version might be more efficient) So if you want the string which you have copied to be used in another function (as it is created in heap section) you can use strdup, else strcpy is enough.

strcpy vs. memcpy

what could be done to see this effect Compile and run this code: void dump5(char *str); int main() { char s[5]={‘s’,’a’,’\0′,’c’,’h’}; char membuff[5]; char strbuff[5]; memset(membuff, 0, 5); // init both buffers to nulls memset(strbuff, 0, 5); strcpy(strbuff,s); memcpy(membuff,s,5); dump5(membuff); // show what happened dump5(strbuff); return 0; } void dump5(char *str) { char *p = … Read more