I am making a program in C that would read a document with a number (supposedly long) and would put them in a dynamic array and then sort the array. I keep on getting the error free(): double free detected in tcache2 and am unsure if it is because of the push function or because of the way I implemented getting each line in the document. Any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
void push(long *arr,long value, int *size){
//printf("%ld",value);
arr = realloc(arr,8 + (8 * (*size + 1))); //allocate 4 more bytes to the arr
arr[*size] = value; //add the value to the end of array
*size = *size + 1; //increase size of array
}
int cmpfunc (const void * a, const void * b) {
return ( *(long*)a - *(long*)b );
}
int main(int argc,char** argv){
if(argc != 2){
fprintf(stderr,"Error too many arguments");
exit(1);
}
FILE *fp = fopen(argv[1],"r+");
if(fp == NULL){
fprintf(stderr,"Error file not found, Error Number: %d\n",errno);
exit(1);
}
int size = 0;
long* arr = (long*) malloc(8); //allocate some mememory to be able to store data points from the file
char str[256]; //create a string capable of storing each singluar line, 10 because the max amount of
while(fgets(str,sizeof(str),fp)){
printf("%s",str);
push(arr,atol(str),&size);
}
qsort(arr,size,8,cmpfunc);
fclose(fp);
return 0;
}