c - segmentation fault (dumped core) -


i tried run following program got error message

"segmentation fault (dumped core)"

my code:

 #include <stdio.h>  #include <stdlib.h>  #include "serialsource.h"   int main()  {     file *pfile;    char *filename="/home/menen/datafiles/t2.txt";    pfile=fopen(filename, "r");    if (pfile == null)     {        printf("can not open file  /home/menen/datafiles/t2.txt");         exit(1);     }       int i;     char ch;     char val[4];     for(i=0 ;i<10;i++)     {       int count=0, j=3;       ch=getc(pfile);       while (ch != '\n')       {         count++;         if (count>=62)         {           val[j]=ch;           printf("%c ", val[j]);           j--;         }         ch=getc(pfile);        }       putchar('\n');      }      fclose(pfile);     exit(0);    } 

can me finding issue in code?

in case,

 val[j]=ch; 

with unbound value decrement of j, can go -ve, , access invalid memory in turn invokes undefined behaviour.

general suggestion: check validity of index value you're going use.

that said, getc() returns int value. @ times, returned value may not fit char. change

 char ch; 

to

int ch = 0; 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -