fclose(in) segmentation faulting - c

I have reduced the program with comments, down to this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE * in;
in = fopen(argv[1], "r");
fclose(in);
fprintf(stderr, "clear **** \n");
return(0);
}
yet it still segfaults. Output is:
clear
Segmentation Fault
I know it's fclose(in) that's causing the problem, I just don't know why. For whatever reason, fclose(out) works perfectly fine.

First thing you should do is something like:
in = fopen(argv[1], "r");
if (in == NULL)
printf ("Could not open file '%s'\n" argv[1]);
else
fclose(in);
There's no guarantee in your original code that the fopen is actually working, in which case it will return NULL and the fclose will not be defined behaviour.

Related

Programm crashing at fgets() in c

when I run my Program, which should read a simple File, it just crashes at the fgets() function. I get no errors in my IDE or from gcc. I know that there are similar Posts, but I couldn't figure out the Problem with them. So here is my code, and thanks for help!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char a[64];
int main() {
FILE* fp;
fopen("Memory.mem", "r");
fgets(a, 64, (FILE*)fp);
printf("%s\n", a);
// the getchar is just that the Program doesn't close it self imeadiatly
getchar();
return 0;
}
//In the Memory.mem file is just "abcdefg"
The problem is when you fopen you don't actually save the returned file pointer.
When you call fgets fp is uninitialized, thus causing undefined behaviour.
You can fix it by instead of doing this:
FILE* fp;
fopen("Memory.mem", "r");
do this:
FILE* fp = fopen("Memory.mem", "r");
Also note that it is good practice to put a check if opening the file was successful.
FILE* fp = fopen("Memory.mem", "r");
if(fp == NULL){
printf("Couldn't open file!\n");
return EXIT_FAILURE;
}
And you should close the file once you are done using it with:
fclose(fp);

C fscanf segmentation fault error "No source available for "flockfile() at 0x7fff855e6d39"

I'm currently working on an old coding problem from USACO in C. Here are the first couple lines of my code, in which I am trying to use the fscanf() function to grab the first value, an int, from the blocks.in file:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fin = fopen ("blocks.in", "r");
FILE *fout = fopen ("blocks.out", "w");
int i,j;
int linecount = 0;
int alphabetCount[26];
fscanf(fin," %d",&linecount);
Running gdb (as a part of the Eclipse C/C++ IDE), I consistently get a segmentation fault error on the line:
fscanf(fin," %d",&linecount);
The error consistently reads:
No source available for "flockfile() at 0x7fff855e6d39"
I haven't been able to source the issue. I've not had any problems with this in the past. Do you see what is wrong, or have a better solution/function with which to extract the data?
I suspect that there is no blocks.in file in the directory from which you run the program. Even if the file is present, it may not open successfully. Some simple error-checking could help you avoid problems here:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fin;
FILE *fout;
int i,j;
int linecount = 0;
int alphabetCount[26];
if ((fin = fopen("blocks.in", "r")) == NULL) {
fprintf(stderr, "Unable to open input file\n");
exit(EXIT_FAILURE);
}
if ((fout = fopen("blocks.out", "w")) == NULL) {
fprintf(stderr, "Unable to open output file\n");
exit(EXIT_FAILURE);
}
fscanf(fin," %d",&linecount);
return 0;
}

.txt file extension in terminal

How come when I type in "(filename).txt" as part of one of the argument in terminal my code doesn't run and gives me a segmentation fault (core dumped)? but if I type "(filename)" instead then the code runs perfectly?
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv){
FILE *inFile = fopen(argv[1], "r");
FILE *outFile = fopen(argv[2], "w+");
char ch = fgetc(inFile);
while(ch != EOF){
fputc(ch, outFile);
ch = fgetc(inFile);
}
}
I skipped error checking writing this small sample code of what I mean. Terminal input would be
"./(program name) (filename).txt (filename2).txt" but this produces a segmentation fault (core dumped)
Whereas, if I type this in
"./(program name) (filename) (filename2) without the .txt file extension the code runs
If you put a debug statement as the first thing in your program printing the contents of argv[1] and argv[2] then you will be able to see the problem and we won't have to guess exactly what you are trying to do. It is very hard for us to understand this issue with a MCVE because you are opening files that exist on your computer but which might not exist on ours. So it could crash on your machine, but have some different error on mine.
"I skipped error checking" ... well that's fine when things work, but here something is going wrong: why not check the return codes and print out the error if there is one. For example:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv){
FILE *inFile;
FILE *outFile;
if (argc < 3) {
fprintf("Only got %d arguments!\n", argc);
exit(1);
}
printf("arg1: %s, arg2: %s", argv[0], argv[1]);
inFile = fopen(argv[1], "r");
if (inFile == NULL) {
perror("Failed on in file: ");
exit(1);
}
outFile = fopen(argv[2], "w+");
if (outFile == NULL) {
perror("Failed on out file: ");
exit(1);
}
int ch = fgetc(inFile); /*as per comments this should be int */
while(ch != EOF){
fputc(ch, outFile);
ch = fgetc(inFile);
}
}
Nothing in your program should behave differently depending on the name of the input or output file.
But you don't check whether the fopen() calls succeeded.
I think what's happening is that the input file with the .txt extension simply doesn't exist. This causes fopen to fail, returning a null pointer, which you then assign to inFile. fgetc(inFile) then crashes.
Always check whether your calls succeeded or failed.
And as I mentioned in a comment, you need to assign the result of fgetc() to an int, not a char. It returns either a character value or the negative value EOF.
In addition you don't need two calls to fgetc, one before the loop and the other in the loop.
Suggested reading: section 12 of the comp.lang.c FAQ.

fprintf not working C

I'm trying to make a simple program that writes to a .txt file, but this code won't work.
#include <stdio.h>
#include <string.h>
#include "main.h"
int main(int argc, const char * argv[])
{
FILE *f = fopen("text.txt", "w+");
char c[256];
printf("What's your name?\n");
scanf("%s", c);
fflush(f);
if (c!=NULL)
{
printf("not null\n");
int q = fprintf(f, "%s", c);
printf("%d", q);
}
else
{
printf("null\n");
}
printf("Hello, %s\n", c);
fclose(f);
return 0;
}
The printf returns that it's not null, and the int q returns whatever the length of the char is. Why isn't this writing to the file?
the printf returns that it's not null,
Thats because c is not null , since you have scanned your name string into it.
Why isn't this writing to the file?
The program is working fine , on my system.
-- Edit --
FILE *f = fopen("text.txt", "w+");
if (NULL == f)
perror("error opening file\n");
By doing the error handling this way , the exact reason (in your case permissions) , would be displayed,
Turns out I wasn't running with the correct permissions. Stupid mistake on my part.
First off, you've declared c in local scope, so it will never be NULL. If you want to check whether or not the user entered anything, check the length of c after you've scanned in the string:
if (strlen(c) == 0) {
///
}
Second, check whether or not you have permission to write to the current working directory. You should be checking the return value of fopen:
if (!f) {
fprintf(stderr, "Failed to open text.txt for writing\n");
}

Segmentation fault

Here is my code.
#include<stdio.h>
int main(int argc,char** argv)
{
FILE* fp;
fp=fopen(argv[1],"r");
struct element{
int value;
char activity;
};
typedef struct element element;
element a;
printf("%d",feof(fp));
}
Now if I don't give the last printf command it does not give me a segmentation fault, but if I give it printf it gives me a seg fault. Why?
I got the answer to my prev problem, now i have another problem
i had .txt appended to my input file in my makefile. Now i have another problem. on command make it gives error.
0make: *** [a.out] Error 1
why?
Check the return value of fopen (well, check the return value of any call), it probably failed to open the file.
Because you do not specify the file in a command line arguments, or because the file you have specified there could not be opened for some reason. In that case, fopen returns NULL, and when you pass that NULL to feof it crashes the program. You have to check return values and error codes, especially when functions may return NULL.
The correct code may look something like this:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
FILE *fp;
if (argc < 2)
{
fprintf (stderr, "Please specify the file name.\n");
return EXIT_FAILURE;
}
fp = fopen(argv[1], "r");
if (fp == NULL)
{
perror ("Cannot open input file");
return EXIT_FAILURE;
}
printf ("%d\n", feof (fp));
return EXIT_SUCCESS;
}

Resources