I'm writing a Vanilla File read code.
Most of it look like this.
Firstly the header file file.h
// fheader.h
#ifndef __file_h__
#define __file_h__
// start from here
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void readFile(FILE *fr);
FILE* openFile(char *file_name);
#endif
the main file fmain.c
#include "fheader.h"
void readFile(FILE *fr) {
// Added Printf
printf("\n...\n");
printf("\n...\n");
printf("\n...\n");
printf("\n...\n");
char *buffer = calloc(sizeof(char),1);
while(!feof(fr)) {
fread(buffer,sizeof(char),1,fr);
printf("%s\n",buffer);
}
free(buffer);
return;
}
FILE* openFile(char *file_name) {
// printf("the file name that is going to be opened is %s",file_name);
FILE *fr;
fr = fopen(file_name,"r");
return fr;
}
int main(int argc,char *argv[]) {
if(argc < 2) {
printf("USAGE: ./file test.txt\n");
return 1;
}
if (argc > 2) {
printf("ERROR: Too many argument\n");
return 1;
}
FILE *fr;
char *file_name = calloc(strlen(argv[1]),sizeof(char));
strncpy(file_name,argv[1],strlen(argv[1]));
fr = openFile(file_name);
printf("\nReading from file\n");
readFile(fr);
fclose(fr);
free(file_name);
return 0;
}
I compiled the code using following command
gcc -g3 -Wall fmain.c -o file.o
When I ran the code
./file.o "~/workspaces/myWork/C_experiment/test.txt"
I see Segmentation fault: 11
But when I run the above program in lldb I work and exit with return code 0
lldb ./file.o
(lldb) run "~/workspaces/myWork/C_experiment/test.txt"
// output of the file
Process 28806 exited with status = 0 (0x00000000)
(lldb) quit
Now, I'm clueless as to how to debug the code and find the Seg Fault reason.