-
Segmentation Fault Again
I dont see anything different, if anything this code is easier than it was
Code:
char str1[1000] = "";
char str2[1] = "^";
char str4[1001] = "";
printf("Enter : ");
fgets (str1, sizeof str1, stdin);
strcpy(str4,str1);
strcat(str4,str2);
FILE *fp = fopen ("news.dat", "a");
fprintf(fp,"%s",str4);
fclose(fp);
-
> char str2[1] = "^";
This is not a 'C' string - it has no \0 terminating it.
As such, your code just roams through memory until it either crashes or finds a \0
Either way, it's broken
This has a \0, and it saves all that tedious counting
This is even better, the run-time overhead is much less since the string itself isn't copied into an array.
The down side is, you can't modity such strings with say str2[0] = '!';
-
Still has Segmentation Fault even with changes you have suggested. I had this problem and fixed it by entering the sizes of my strings i've made some changes and its back, thing is this code does work, its writes to the file just what i want, but then Segmentation Fault and the program closes
-
1) Where does it seg fault?
2) Check to make sure fopen() didn't return NULL
-
Posting an actual complete program as well would help - random snippets of where you think the problem is doesn't work.
-
>thing is this code does work, its writes to the file just what i want,
>but then Segmentation Fault and the program closes
You have a slightly skewed understanding of working code. You're also not off to a good start here. We make it very clear what we need to help you solve your problem, but you seem to be fighting us the entire way. In the end, nobody will want to help you because it's just not worth the effort.
-
I concur with Prelude's statement.
Though, I have had run-ins with Segmentation Fault's and Stack Overflow's many times. With only a glimpse of your code, here is my advice.
Look for any pointers that may be un-initialized, modified as a literal or constant, de-referenced while a NULL value, or accessing memory that isn’t yours.
Things that segmentation faults/violations are typically out-of-bounds array references and/or references through un-initialized or mangled pointers. Look very closely in your program for bizarre things like that.
There are a number of methods for finding out where the program went out of bounds. One method is to use printf() statements to determine how far the program is getting before it crashes, and to print out the contents of interesting variables.
All in all, this comes down to where it generally means that your program tried to access memory it shouldn't have, invariably as a result of stack corruption or improper pointer use.
- Stack Overflow