Segmentation fault and C strings

Hello,

I was deliberately trying to generate a seg fault here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#include <string.h>
int main()
{

	char s1[] = "aeiou";
	char s2[11] = "0123456789";
	char s3[5];

	printf("output 01 -------------\n");
	printf("%s\n", s1);
	printf("%s\n", s2);
	printf("%s\n", s3);
	printf("-----------------------\n");

	strcpy(s1, s2);

	printf("output 02 -------------\n");
	printf("%s\n", s1);
	printf("%s\n", s2);
	printf("%s\n", s3);
	printf("-----------------------\n");

	return 0;
}


Why is it that line 16 causes this error and i still get output2?!

Thanks
Char array s1 is initialized by "aeiou", so 5 characters+NULL=6. Size of s1 is 6. In line 16 you try to copy text from s2 to s1, but size of s2 is bigger than s1. It causes error. Consider using strncpy or increase size of s1 array.
Ok ... i get that ... but check the output:

1
2
3
4
5
6
7
8
9
10
11
output
output 01 -------------
aeiou
0123456789
����0123456789
-----------------------
output 02 -------------
0123456789
0123456789
����0123456789
-----------------------
Segmentation fault


What exactly causes the segmentation fault?
Showld it not stop before output2?
Last edited on
I don't understand what's your problem exactly.

Btw, why do you print s3?
Topic archived. No new replies allowed.