0

Why do I get a segfault?

https://code.sololearn.com/cT1cn35GJiw8/#c When I compile and run this code (which will be used for a virtual LMC), I get a segmentation fault, and I don't understand where is my mistake... Can you help me? Infos: Compiling with GCC 7 on linu (OpenSuSE 15.1).

16th Dec 2019, 4:42 PM
Gwlanbzh
Gwlanbzh - avatar
7 Answers
+ 3
Hi SpaceNerd Well there are some problems with your code. Nevertheless the reason for segfault is problably because you are using fgets() to read words of three letters but when you declare you matriz you defined it as Matrix[100][3] meaning that you forgot that the function will add a '\0' to mark the end of the string. So, just declare the matrix columns with one more space, as Matrix[100][4]. By the way, you should also check if the file is open before manipulating it. Do a if(prog == NULL) exit(-1);
16th Dec 2019, 5:17 PM
Mark
+ 3
Try this: #include <stdio.h> #include <stdlib.h> #define RAM_LENGTH 100 int main(int argc, char * argv[]){ switch (argc) { case 1: fprintf(stderr, "Error: please enter a file to work on.\n"); exit(5); case 2: break; default: fprintf(stderr, "Error: too many arguments."); exit(7); } FILE * prog = fopen(argv[1], "r"); if(prog == NULL) exit(-1); char RAM[RAM_LENGTH][4]; int ram_index = 0; while(!(feof(prog)) && ram_index < RAM_LENGTH){ fgets(RAM[ram_index], 3, prog); ram_index++; } fclose(prog); //By using ram_index the program show only the words read. for (int x = 0; x < ram_index; x++){ printf("%s\n", RAM[x]); } return 0; }
16th Dec 2019, 5:25 PM
Mark
+ 1
Mark thanks a lot it worked perfectly!!
16th Dec 2019, 6:13 PM
Gwlanbzh
Gwlanbzh - avatar
0
De rien, SpaceNerd
16th Dec 2019, 6:43 PM
Mark
0
Oh un français :-)
16th Dec 2019, 7:48 PM
Gwlanbzh
Gwlanbzh - avatar
0
Je n'en ai pas vu beaucoup ici
16th Dec 2019, 7:50 PM
Gwlanbzh
Gwlanbzh - avatar
0
J'ai déjà trouvez autres français ici. En effet, il y a la liste de classification local de XP. Là tu peut trouvez la liste des utilisateurs français.
16th Dec 2019, 9:50 PM
Mark