
- Forum
- Programming Talk
- C and C++
- Program Crashing
Program Crashing
This is a discussion on Program Crashing within the C and C++ forums, part of the Programming Talk category; I have written my C code as below: #include<stdio.h> main() { char *e = "WELCOME"; char *f,*g; f = e; ...
-
Program Crashing
I have written my C code as below:
#include<stdio.h>
main()
{
char *e = "WELCOME";
char *f,*g;
f = e;
g = e+strlen(e)-1;
printf("%c, %c",*f,*g);
*f=*g;
printf("%c, %c",*f,*g);
}
What I am trying out is trying to first print out the first and the last letter of the given string and then assign the last letter to the first and print the first and last letter with the same letter as last letter. That is first to print W and E and then to print E E. But when I tried the above program it is crashing and is giving me segmentation fault. I could not figure out the reason. Can someone help me out?
-
Program Crashing: Answer
#include<stdio.h>
main()
{
char *e = "WELCOME";
char *f,*g;
f = e;
g = e+strlen(e)-1;
printf("%c, %c",*f,*g);
*f=*g;
printf("%c, %c",*f,*g);
}
Hi,
The above program crashes because:
till the first printf everything is fine. but later you are trying to put the address contained in g to f. and since this cannot be done and hence the error.
I hope i have cleared your doubt.
Regards,
Gayatri
-
Yes as our friend has suggested till the first printf all is good. The program if you debug you would find it crashing at the second printf only. This is because you are trying to access and write to a protected memory space. This type of protected memory space can be used for reading but when you try to write into this you would face such error. To correct the above program just change as
char e[] = "WELCOME";
char *f = e;
...........
...........
and proceed with the other code and your code should work fine.
-
Sponsored Ads

Reply With Quote





