C memory question
char buffer[10];
strcat(buffer, "hi");
printf("%s", buffer);
In the above code, it prints some weird symbol or number followed by the "hi", I know strcat is appending to buffer. And I normally zero the memory in buffer. But i'm curious why I usually have to do that.
If i do printf("%i", buffer);
without the strcat, it just prints a random number. What i开发者_C百科s that number? Could anyone explain or link to a tut that explains what is in buffer, before I fill it with anything?
"buffer" is a 10 byte region on the stack, and it'd contain whatever was last written to that region of memory. When you strcat, it would concatenate "hi" after the first null byte in that region (So if the first null byte is beyond 10 bytes, you'd overwrite something on the stack). When you print without zeroing, it'd print the bytes until the first 0 (null). Again, this might print beyond the 10 bytes.
When you printf (%I, buffer), you print the address of that location.
First up, you need to zero-init the buffer:
char buffer[10] = {0};
buffer[0] = 0; /* As R.. points out, initializing all elements is excessive. */
Second, the number is the address of buffer
, as a decimal. If you really want to print that, you are better off printing:
printf("%p\n", buffer);
You need a terminating '\0' to mark the end of the string, use
strcpy(buffer,"hi");
strcat() tries to append to an already existing string which is assumed to be '\0' terminated. Your buffer isn't initialized.
do a memset(buffer, 0, 10)
to zero the memory first, before appending.
The strcat() function appends the src string to the dest string, overwriting the null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result.
buffer
is not '\0'
terminated, as it is not initialized, we do not know what it contains. Therefore it is an undefined behavior. You should first make sure the buffer is '\0' terminated.
And the number printed is not a random number it is the starting address of the buffer.
精彩评论