c - strange Segmentation fault (core dumped) on matrix -
so, have part of code:
for (lin = 0; lin < linhas_mat1; lin++) { fgets(linha_s, max_linha, matriz1_file); buffer = strtok(linha_s, " "); (col = 0; col < colunas_mat1; col++) { printf ("\ncoluna: %d", col); if (&matriz1[lin][col] == null) printf ("erro"); matriz1[lin][col] = atoi(buffer); buffer = strtok(null, " "); } }
it puts matrix file memory. open , allocation didn't give errors (at least think). what's strange error seems occur (discovered printing number of current line) on last 2 elements (before last code above or last element if add prints, that's stranger) , if matrix has 5 lines or more. previous lines added memory without problem, can't see why last elements give problems. has clue what's problem or tips in how can find issue?
the code has no problem. possible reason can see is, when input file has less columns specified, cause segmentatioin fault.
here full version of code, added initializations
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int lin, col, linhas_mat1, colunas_mat1; char* buffer; char linha_s[1023]; int matriz1[8][5]; linhas_mat1 = 8; colunas_mat1 = 5; const int max_linha = 20; file *matriz1_file = fopen("aa.txt", "r"); (lin = 0; lin < linhas_mat1; lin++) { fgets(linha_s, max_linha, matriz1_file); buffer = strtok(linha_s, " "); (col = 0; col < colunas_mat1; col++) { //printf ("\ncoluna: %d", col); if (&matriz1[lin][col] == null) printf ("erro"); matriz1[lin][col] = atoi(buffer); printf("%d ", matriz1[lin][col]); buffer = strtok(null, " "); } printf("\n"); } }
if give following file input, matrix values without problem, unless remove column it.
1 2 9 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
Comments
Post a Comment