My original task is: Given a file of numbers, I have to find all pairs (a pair is just 2 numbers; they cannot be consecutive) that fulfil a certain condition.
To do that, I've decided to create an array where I will store all the numbers. I have a ~11000 Kbyte file of numbers (the number of numbers is ~1,5*10^9), and I need to read all of them from the file and store them in an array.
Numbers in the file are arranged like this; 0 < number <= 100000:
10
20
30
40
50
60
The first thing I decided to do was to create just a regular array int arr[150000000]
. But this won't do due to stack overflow.
Then I decided to use calloc
.
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *file = fopen("nums.txt", "r");
int str_size = 8;
char str[str_size]; // 0 < number <= 100000, so using the length 8 (6 digits + '\n' + null-terminating byte) is enough.
int size = 2000; //Initial capacity
int *a = calloc(size, sizeof(int)); //The array
int i = 0;
while( ((fgets(str, str_size, file) ) != NULL)) { //read a line from the file (a line = 1 number)
if(atoi(str)!=0) // '\n' is on the end of each line, so fgets() function will read an empty line and return 0, we don't want that.
{
a[i] = atoi(str); //Convert a string to int and storing the value in the array
i++;
}
a = realloc(a, sizeof(int)*(size*2) ); //And then I realloc my array, multiplying the size by 2.
size = size * 2;
}
a[i] = -1; //When the flow of numbers ended, I mark the end with -1.
fclose(file);
free(a);
return 0;
}
This code works well for smaller files (100 Kbyte files), but fails for larger files, returning the following:
realloc(): invalid next size
Aborted (core dumped)
As far as I understand, this means that my computer cannot allocate more memory. So what can I do?
EDIT
I understand my first error. I reallocated the array's size, but I didn't increase the size
variable itself. But it didn't help me, now I get the Segmentation fault (core dumped)
instead.