Search code examples
csegmentation-faultprogram-entry-point

Seg fault before main even runs?


I'm receiving a segmentation fault before my main even runs any significant code capable of causing a seg fault. Namely, printf("before main functionality starts\n"); is not running.

What could be causing this problem?

 int main() {
  printf("before main functionality starts\n"); 
  person* people = create();
  
  //Make new file and write into it
  printf("\nWriting into file\n");
  char file_name[] = "people_list";
  int file_number = open(file_name, O_CREAT|O_WRONLY, 0644); //only owner can read/write, rest can only read

  int error_check;
  error_check = write(file_number, people, sizeof(&people) ); //reads array into file
 
  if(error_check < 0) {
    printf("ERROR: %s\n", strerror(errno));
    return -1;
  }
  close(file_number);

  //Read from new file
  printf("\nReading from file...\n");
  person* new_people[10];
  file_number = open(file_name, O_RDONLY); //reopens file, now with data
  error_check = read(file_number, new_people, sizeof(people));
  if(error_check < 0) {
    printf("ERROR: %s\n", strerror(errno));
    return -1;
  }
  close(file_number);


Solution

  • If you want to see output immediately then you need to flush the handle (using fflush(stdio)). Your program is very likely crashing after the printf call that it issues immediately.

    IO is also flushed on end of line, so if you have your debug statement end in '\n' then it will be displayed and you will find where your segmentation fault is happening.