I´m writing a small C program that reads a text file and the prints it´s contents on screen. I do get the prints, but at the end of the printing I get a segmentation fault. Also, if I uncomment the atoi function I only get the first print and then a segmentation fault.Can anyone tell me what my error is?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/stat.h> /* For mode constants */
#include <sys/types.h>
#include <fcntl.h> /* For O_* constants */
int sudoku[9][9];
int main(int argc, char *argv[]){
if(argc!=2){
printf("error en numero de parametros, el directorio de archivo de sudoku.\n");
return -1;
}
char *directorio = argv[1];
//printf("el directorio es: %s \n", directorio);
int fp;
fp=open(directorio,O_RDWR);
if(fp<0){
printf("error al leer el archivo");
return -1;
}
char *data = mmap(0, 4096, PROT_READ, MAP_SHARED, fp,0);
if (data == -1) {
perror("mmap");
exit(1);
}
int i=0;
for(i=0; i<81 ; i++){
printf("data : %c \n",data[i]);
//int val =atoi(data[i]);
}
if ((munmap(data,4096)) != 0) perror("!mumap failed");
fclose(fp);
}
atoitakes a character array (string), in your case you want to use single characters. This will most likely crash since there isn't a null in the end, unless the sunspots are favorable. In any case you won't get what you want (a single character's numeric value)534678912672195348198342567859761423426853791713924856961537284287419635345286179it is exactly 81 characters long. I don´t really know how to get the debugger going. I´m totally new to Cdata[i] - '0'rather thanatoianyway, assuming you fixed all the other items wrong in the posted code.