ramnarayanan
ramnarayanan

Reputation: 117

Segmentation Fault Core Dump Error

This is my C program and I am using g++ compiler. After compilation, when I run the code, it gives a segmentation fault (core dumped) error:

#include <stdio.h>
#include <stdlib.h>

int main(){

  FILE *fp;

  fopen("sample.txt", "w+");

  fprintf(fp, "%s %s %s %d", "We", "are", "in", 2016 );

  fclose(fp);

  return 0;
}

Please guide.

Upvotes: 0

Views: 147

Answers (2)

Philip
Philip

Reputation: 1606

fprintf prints to the file given by the file pointer fp. In this case, fp is only declared and never assigned a value, hence is null. When fprintf uses the null pointer it causes a seg fault. You should have done fp = fopen(...) so the pointer isn't null.

Upvotes: 0

ramnarayanan
ramnarayanan

Reputation: 117

Just found out: Simply assign the file open function to my file descriptor.

fp = fopen("sample.txt", "w+");

Upvotes: 2

Related Questions