Seg Fault with fgets and fputs - Probably easy to fix, but I don't know how.

Here's my code:
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>
#define size 768

int main()
{	
  
  char *listName = (char*) malloc(size);
  char *createList = (char*) malloc(size);
  char *iName = (char*) malloc(size); //String for naming/getting Axx Filename
  char *oName = (char*) malloc(size); //String for naming merger file
  char *header = (char*) malloc(size);
  
  for(int run=55678;run<=55678;run++)
    //for(int run=55678;run<=56152;run++)
    {		
      sprintf(listName, "e%d.list", run);
      sprintf(createList, "ls -1 coh_edge_POL_0%d* > %s\n", run, listName);
      system(createList); //Create and populate your eRunNo.list file with related RunNo_Axx filenames.
      FILE *list = fopen(listName,"r"); //Open eRunNo.list (DO NOT CLOSE THIS FILE UNTIL THE END)
      fgets(iName, 1024, list); //Get first filename in list
      FILE *inputf = fopen(iName, "r"); //Open Axx file. 
      free(createList);
      free(listName);
      free(iName);		
      
      //Open Merge File
      sprintf(oName, "POL_EDGE_%d.txt", run);
      FILE *outputf = fopen(oName, "w"); //Open merged file  (DO NOT CLOSE THIS FILE UNTIL THE END)
      free(oName);
      
      //Begin 'Get 3 Headers'
      fgets(header, 1000, inputf);     
      fputs(header,outputf);
      free(header);
      fgets(header, 1000, inputf);     
      fputs(header,outputf);
      free(header);
      fgets(header, 1000, inputf);
      fputs(header,outputf);
      free(header);
      //End 'Get 3 Headers'
      
      fclose(inputf); //Close Axx file
      
      //Close remaining Files
      fclose(outputf); //Close Merge File
      fclose(list); //Close Run List	
    };
  
  
  return 0;
}


I'm running a GUI front-end for GDB, known as DDD. It outputs a segfault error when trying on line 33, so this code:
1
2
3
      fgets(header, 1000, inputf);     //Seg faults when I step here with GDB
      fputs(header,outputf); 
      free(header);


The error message from GDB/DDD:
1
2
3
Program received signal SIGSEGV, Segmentation fault.
0x0000003ccba61d2d in fgets () from /lib64/libc.so.6
Missing separate debuginfos, use: debuginfo-install gcc.x86_64 glibc.x86_64


I have a 64-bit machine with 512mb of ram running (maybe 1gb), running Fedora. This is my office machine so I don't know too much about it.
Last edited on
When I run this program on my mac, I get a KERN_PROTECTION_FAILURE message from DDD. This mean's im trying to access some shared-memory which I can't.
Specs on mac: 64 bit machine with 4 gigs of RAM.
Never mind, I fixed it. I started using fscanf(); instead of fgets(); on line 21, and switched from malloc() to defined string arrays and everything worked.
Topic archived. No new replies allowed.