I try to create a 2D-Array and try to fill it with integers from a file. But when I run my program I get a Segmentation Fault at this line according to Valgrind:
*(array_valid_char++) = read_char;
Here is my code:
#include <stdio.h>
#include <stdlib.h>
int* f(char* name_file_in, int key_length)
{
FILE *file_in;
int* array_valid_char = malloc(95 * sizeof(int));//array of validated characters
int count_char = 0;//count number of characters in file_in
int read_char;//character being read
file_in = fopen(name_file_in,"rb");
if(file_in)
{
while ((read_char = fgetc(file_in)) != EOF)//browse the entire file
{
if ((count_char % key_length) == 0)//test if character's position in file belongs to the modulo of the key
{
for (int i = 0; i < 95; i++)//browse the entire array tabLatin
{
*(array_valid_char++) = read_char;//read character put into array of validated characters
}
}
count_char++;
}
}
if(file_in){fclose(file_in);}
return array_valid_char;
}
int** C1(char* name_file_in, int key_length)
{
int **array_valid_keys = malloc(key_length * sizeof(int*));//array of array filled with all valid characters for a character of the key
for (int i = 0; i < key_length; i++)
{
array_valid_keys[i] = malloc(95 * sizeof(int));
}
for (int i = 0; i < key_length; i++)
{
array_valid_keys[i] = f(name_file_in,i + 1);//for each character'position of the key is assigned an array given by f
}
return array_valid_keys;
}
int main(int argc,char* argv[])
{
int key_length = atoi(argv[2]);
int** array_valid_key = C1(argv[1], key_length);
for(int i = 0; i < key_length; i++)
{
for(int j = 0; j < 95; j++)
{
printf("[%d] ",array_valid_key[i][j]); //printing all valid characters for each character of the key
}
printf("\n");
}
return(0);
}
What is wrong with that code?
If I understand correctly, a Segmentation Fault is an exceeding of memory allocated by the program. So my problem should be in the size of my 2D-Array or in how I try to fill it.
However, I have allocated a number of key_length columns like this:
int **array_valid_keys = malloc(key_length * sizeof(int*));
And, I have allocated each column to be an array of 95 cases with:
for (int i = 0; i < key_length; i++)
{
array_valid_keys[i] = malloc(95 * sizeof(int));
}
When I fill this 2D-Array with
for (int i = 0; i < 95; i++)//browse the entire array tabLatin
{
*(array_valid_char++) = read_char;
}
It shouldn't get an error because my loop is in the [1, 95] intervall (which is the size of each columns of my 2D-Array).
The other explanation is that one of my pointers are dangling according to this question but how?