Your brief description of malloc is not incorrect. It does reserve memory. More accurately stated, from the link:
"Allocates a block of size bytes of memory, returning a pointer to the
beginning of the block."
(emphasis mine)
But that is not the only consideration for using it in preparation for creating a C string
.
In addition to understanding malloc()
, Undefined Behavior (1) is good to be aware of, and how at best will cause buggy behavior, but possibly much worse.
By creating memory for 3 bytes, and writing a string with more than two characters (and a NULL terminator) you have invoked undefined behavior (2). Sometimes it will seem to work, but others it will not. In this case, you have written to memory that you do not own. If that memory is not also concurrently owned by another variable. It is likely to appear to you that all is normal, as is demonstrated by the results you show in your post. But if it is owned, and being used by another variable, the operation of writing to that location will fail. The second of these scenarios is the better of the two. The first is especially bad because it will cause your program to appear fine, possibly for hours, but the first time a conflict occurs, it will fail.
Keep in mind also, the definition of a string in C
is a null terminated character array:
char string[20];
char string2[3];
strcpy(string, "string content");//will always work
strcpy(string2, "string content");//may or may not appear to work
string
would appear in memory as:
|s|t|r|i|n|g| |c|o|n|t|e|n|t|\0|?|?|?|?|?|
Where ?
can be any value.
there is no guarantee what string2
will contain.
Regarding your statement: However the strange thing is, I never get any errors in the first line..., because undefined behavior(3) is by definition unpredictable, the following may or may not help you to see the effects, but because of the over exagerated values and assignments, it will likely cause an access violation at some point...
char shortStr[2][3] = {{"in"},{"at"}};//elements [0] & [1] will be provided memory locations close in proximity.
char longStr[100]={"this is a very long array of characters, this is a continuation of the same thing."};
strcpy(shortStr[0], longStr);
This will likely result in an error because shortStr[1]
, although not guaranteed, is in a memory location that will prevent the copy from happening without a memory access violation.