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 *...
|
|||||||
| Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
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. |
![]() |
| Thread Tools | |
|
|
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| comp.lang.c Answers (Abridged) to Frequently Asked Questions (FAQ) | Steve Summit | Tech FAQ | 0 | 06-15-2004 07:00 AM |
| comp.lang.c Answers (Abridged) to Frequently Asked Questions (FAQ) | Steve Summit | Tech FAQ | 0 | 06-01-2004 07:01 AM |
| comp.lang.c Answers to Frequently Asked Questions (FAQ List) | Steve Summit | Tech FAQ | 0 | 06-01-2004 07:00 AM |
| comp.lang.c Answers (Abridged) to Frequently Asked Questions (FAQ) | Steve Summit | Tech FAQ | 0 | 05-15-2004 07:00 AM |
| Apple II Csa2 FAQs: Telecom Hardware & Transfers, Part 20/25 | rubywand@swbell.net | Tech FAQ | 0 | 04-04-2004 08:29 AM |