Josh
Josh

Reputation: 6282

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 is that number? Could anyone explain or link to a tut that explains what is in buffer, before I fill it with anything?

Upvotes: 2

Views: 143

Answers (5)

cnicutar
cnicutar

Reputation: 182744

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);

Upvotes: 3

jman
jman

Reputation: 11626

"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.

Upvotes: 4

phoxis
phoxis

Reputation: 61990

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.

Upvotes: 0

Vinicius Kamakura
Vinicius Kamakura

Reputation: 7778

do a memset(buffer, 0, 10) to zero the memory first, before appending.

Upvotes: 1

stacker
stacker

Reputation: 68992

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.

Upvotes: 2

Related Questions