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).
7 Antworten
+ 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);
+ 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;
}
+ 1
Mark thanks a lot it worked perfectly!!
0
De rien, SpaceNerd
0
Oh un français :-)
0
Je n'en ai pas vu beaucoup ici
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.