Strcopy understanding

Hi,
my code is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string.h>

int main()
{

    char bla[2][4];
    strcpy(bla[0],"haha");
    strcpy(bla[1],"hihi");
    strcpy(bla[2],"huhu");
    printf("%s",bla[0]);
    return 0;
}

My question is, that why does it print out hahahihihuhu / all the strings I added to different indexes?
Let consuder the program step by step.

Here

strcpy(bla[0],"haha");

5 characters (do not forget the terminating zero of the string literal) is copied to bla[0] that has type char[4]. So the fifth character that is '\0' will be copyed in bla[1][0].

Here

strcpy(bla[1],"hihi");

is the same problem. Only the bla[1][0] that contains '\0' will be overwritten by the first character of the string literal. The terminating zero will be written beyond the array.

Here

strcpy(bla[2],"huhu");

you are overwriting the memory that does not belong to the array because the array has acceptable indexes in the range [0, 1].. Again you are overwriting the last terminating zero of the previous operastion.

So you get one long string which occupies the memory beyond the array. The type of the expression b[0] is char[]. So then you use

printf("%s",bla[0]);

the whole string will be outputed.

Last edited on
The program is invalid, the array size is too small.

String "haha" is five characters long.
It is equivalent to { 'h', 'a', 'h', 'a', '\0' }

Thus the terminating null character '\0' falls in the first position of the next string.
Each strcpy will over-write the null byte of the previous string.

The null of strcpy(bla[1],"hihi"); will fall outside boundaries of the array.

In addition, bla[2] is the third entry in an array of just two elements, so it as writing to an area outside the array.

If you want predictable and valid results, change line 7 to read:
char bla[3][5];
Vlad is right, let me show how your memory will look like with all the strcpy's, assuming you correct your bla's size and my written 0 is binary 0:


Beginning Data into bla (4x3 + 1):
0000000000000
First strcpy:
haha000000000
Second strcpy:
hahahihi00000
Third strcpy:
hahahihihuhu0


When printf calculates the length of the string, it goes looking for that 0, but only finds one at the end of all the variables, so prints them all.
Thank you guys very much. I totally forgot about the '\0' char.
Topic archived. No new replies allowed.