I found a lot of similar questions concerning this error, but the answers I found did not help me.
My program works for eleven data points which I read from a list "data.dat" without errors. If I increase the number of data points I get this error I don't understand. The file with my data consists of three columns of float numbers.
Here is a short version of my code.
#define DIM 3
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
// Recursive function to build tree
void my_function(FILE* outFile, double* r, int* idxList, unsigned long int* Nodes, int *node, int n, unsigned long int myKey)
{
unsigned long int myKey1 = myKey;
for(int q=0; q<8; q++)
{
fprintf(outFile, "%d %d %d\n", q, n, *node);
myKey1 = (myKey << 3)|q;
Nodes[*node] = myKey1;
*node += 1;
if(*node < 20)
{
my_function(outFile, r, idxList, Nodes, node, n, myKey1);
}
}
}
int main(int argv, char** argc)
{
FILE *inFile;
inFile = fopen("data.dat", "r");
FILE *outFile;
outFile = fopen("result.dat", "w");
unsigned int n = 15; // Number of points
unsigned int N = n*DIM; // Elements in array
// Array for points
double *r = NULL;
r = (double*)malloc(sizeof(double)*N);
unsigned long int *Nodes = NULL;
Nodes = (unsigned long int*)malloc(sizeof(unsigned long int)*3*n);
for(int i=0; i<3*n; i++)
{
Nodes[i] = 0b0;
}
int *idxList = NULL;
idxList = (int*)malloc(sizeof(int)*3*n);
memset(idxList, -1, sizeof(int)*3*n); // Set all entries to -1
for(int k=0; k<N; k++)
{
fscanf(inFile, "%lf", &r[k]);
}
int node = 0;
unsigned long int myKey = 0b1;
my_function(outFile, r, idxList, treeNodes, &node, n, myKey);
// Close files
fclose(inFile);
fclose(outFile);
// Clean up
free(r);
free(Nodes);
free(idxList);
}
The program works, but if I put more data points to the list, I get the following error.
*** Error in `./myProgram': munmap_chunk(): invalid pointer: 0x0000000000f74810 Aborted (core dumped)
If I comment the section
// Close files
fclose(inFile);
fclose(outFile);
// Clean up
free(r);
free(Nodes);
free(idxList);
of my code, the error disappears. How can I fix this error? Any suggestions?