Hi there, I have a very simple code made of a main.c and a function defined in its own .c and .h files.
Now, within the function I need to increase the size of an array according to the loop index in use.
The problem comes when I allocate the array even before useing the realloc. If I use malloc initially to allocate a multiple of 1000 elements, although the total elements that will be actually used to fill in the array are only about 40, I obtain a segmentation fault. The same happens if I use a realloc trhough the loop.
I hope I have explained myself right and to get some help from any of u!
I report the part of my code where this is done (function PSUP.c).
thank you
/******************************************************************
* PSUP(connectivity_file, nnodes)
*
* Points Surrounding Point (PSUP):
*
* Input:
* - connectivity_file: text file of the connectivity matrix.
* It must contain the conn matrix in the format:
* conn(1:nelem, 1:elnnode)
* where nelem is the mesh number of elements and
* elnnode is the max number of nnode that any element may have.
* ex:
* 2 5 3
* 6 3 1
* 3 1 8
* 9 8 5
* ...
*
* NOTE that the first column does NOT contain the numbering of the elements!!!
*
* - nnodet: Number of points in the mesh
*
* Output:
* - max_psup is the output: maximum number of nodal contacts inside the mesh
*
*
* REFERENCES:
* [1] Lohner,R. (2008), Applied computational fluid dynamics techniques",ed.II, John Wiley and Sons
*
******************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int PSUP(int CONN[][3], int nnode, int nelem, int max_nnode, unsigned int array_numb)
//int PSUP(int **CONN, int nnode, int nelem, int max_nnode, unsigned int array_numb)
{
int _ipoin, _inode, _ielem, _ipoi1, _ipoi2, _istor;
printf("\n #Elements surrounding points#\n");
//Initialize _esup2:
int *_esup1;
// int _esup1[nnode*1000];
int _esup2[nnode+1];
int _nesup[nnode+1];
_esup1 = malloc((sizeof(int))*nnode*1000);
/****************************/
IN THIS PART THERE ARE SOME LINES
WHERE THE ARRAYS USED NEXT ARE ASSIGNED, AND IT WORKS CORRECTLY.
iT IS A LONG PART, SO i DONT PUT IT FOR THE SAKE OF READABILITY.
/****************************/
for(_ielem=array_numb; _ielem<=nelem-1+array_numb; _ielem++){
for(_inode=array_numb; _inode<=max_nnode-1+array_numb; _inode++){
//Update storage counter, storing in _esup1:
_ipoin = CONN[_ielem][_inode];
_istor = _esup2[_ipoin] + 1;
_esup2[_ipoin] = _istor;
// _esup1 = realloc(_esup1,(_istor+1)*sizeof(int));
_esup1[_istor] = _ielem;
}
}
free(_esup1);
return; //*_nesup;
}