Reputation: 794
I do have a question about the Reallocation of memory in C, because I think this is causing a problem which I have for a week now, without finding it. I am you have squared paper and your somebody filled a couple of squares with green colour. So now, I am trying to read the coordinates of the green squares (somebody puts them into the stdin) and then I would like to link them together by looking if they are neighboured together. So in the Cell struct, all the Cells do have coordinates, pointers to potential neighbours and a counter of neighbours. And there is a function called setNeighbours which figures out if they are neighbours and fills the addresses into every object. So my problem is about the reallocation method, because I know this is potentially moving the address block to somewhere else and in reason for that, sometimes (maybe 40% of the times) I am getting wrong results when printing out the results.
The code is below. I know that the reallocation line is the reason, because if I do delete it and just put enough space into the malloc line so there is no need for realloc later, then everything works fine. I guess there is one stupid moment where I am calling for an old address which has changed before, but I cannot see the it. Does one see it?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
typedef struct Square {
long index;
long x;
long y;
struct Square *Above;
struct Square *Below;
struct Square *Right;
struct Square *Left;
int count;
} SquareType;
SquareType *cellArr;
long countSquares = 0;
Example input:
1 3
2 3
3 3
2 2
2 1
3 2
Upvotes: 0
Views: 783
Reputation: 180715
So my problem is about the reallocation method, because I know this is potentially moving the address block to somewhere else and in reason for that, sometimes (maybe 40% of the times) I am getting wrong results when printing out the results.
Indeed, realloc()
does not always put the reallocated block at the same address as the original one. If you reallocate the space containing your structures then you have to assume that any pointers to those structures obtained prior to the reallocation cease to be valid. Your code does not seem to be making that assumption.
There are only a few viable solutions:
Do not rely on pointers into the allocated space, other than the main one you maintain to the beginning of the space. One way to achieve that would be to identify neighbors by their indexes instead of by pointers directly to them. Or,
Set up the pointers only after reading all the data, so that you can be sure all needed reallocations have already been performed. Or,
Avoid reallocating. You can do that either by allocating sufficient space for everything up front (a pretty good option if you have or can get at least a reasonable upper bound on the amount you'll need), or by allocating each structure independently of the others.
Upvotes: 1