c - Segment Fault (Core Dump) Error -


#include<stdio.h> #include<stdlib.h> #include<string.h>  void stringreverse(char* s){     char tmp;     int = 0;     int j = (strlen(s)-1);     while(i>=j){         tmp = s[i];         s[i] = s[j];         s[j] = tmp;         i++;         j--;     }  }  int main(int argc, char* argv[]){     file* in; /* file handle input */     file* out; /* file handle output */     char word[256]; /* char array store words input file */     /* checks command line has correct number of argument */     if(argc !=3){         printf("usage: %s <input file> <output file>\n", argv[0]);         exit(exit_failure);     }      /* opens input file reading */     in = fopen(argv[1], "r");     if(in==null){         printf("unable read file %s\n", argv[1]);     }      /* opens ouput file writing */     out = fopen(argv[2], "w");     if(out==null){         printf("unable read file %s\n", argv[2]);         exit(exit_failure);     }      /* reads words input file , reverses them , prints them on seperate lines output file */     while(fscanf(in, " %s", word) != eof) {         stringreverse(word);         fprintf(out, "%s\n", word);     }      /* closes input , output files */     fclose(in);     fclose(out);      return(exit_success); } 

i keep getting segment fault (core dump) error. doing wrong? out file returned empty, shouldn't happen.

my input

abc def ghij  klm nopq rstuv  w xyz 

and output should be

cba  fed  jihg  mlk   qpon   vutsr  w   zyx 

definitely should spend time learn use gdb , valgrind. code, shouldn't while(i<=j) instead of while(i>=j) @ line 9?

explanation:

the discussion between barmar , loginn did job on explaining why segmentation fault happening here. logic while(i>=j) wrong won't segmentation fault unless have single character (such 'w' in sample input) in input file. why single character input cause segmentation fault? because start loop = 0 , j = 0 satisfies loop condition , go onto = 1 , j = -1 satisfies incorrect loop condition. @ point attempt access invalid address (s[-1]) cause segmentation fault.

if don't have single character in input file program run , print words in output file. won't reverse words because code not enter while loop reverse because of wrong condition. won't cause segmentation fault either.

i hope have explained well.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -