The class:
class Tile {
public:
long long size, joint;
};
My main has:
int main() {
//
double minW, minL;
unsigned tileCap = 10, tileCount = 0;
bool wasTransformed = false;
auto *tiles = (Tile*)calloc(tileCap, sizeof(Tile) );
GetInput(&minW, &minL, &tiles, &tileCount, &wasTransformed);
//etc.
}
The problematic function here is GetInput()
:
void GetInput(double *w, double *l, Tile **tiles, unsigned *tileCount, bool *needTransform) {
//
printf("Min dimensions:\n");
if (scanf("%lf %lf", w, l) != 2)
BadInput();
if (!CorrectSize(*w) || *w == 0)
BadInput();
if (!CorrectSize(*l) || *w == 0)
BadInput();
unsigned tileCap = 10;
*tiles = (Tile*)calloc(tileCap, sizeof(Tile) );
printf("Tiles:\n");
double tileSize, tileJoint;
int argc;
do {
argc = scanf("%lf %lf", &tileSize, &tileJoint);
if(argc == EOF) {
break;
}
if (tileSize == 0 || !CorrectSize(tileSize) || !CorrectSize(tileJoint) || argc != 2)
BadInput();
if(! *needTransform) {
*needTransform = HasFloatingPoint(tileSize) || HasFloatingPoint(tileJoint);
if(*needTransform)
TransformPrevious(*tiles, *tileCount);
}
if(*needTransform) {
//transform this
tileSize *= 10;
tileJoint *= 10;
}
(*tiles)[*tileCount].size = (long long)tileSize + (long long)tileJoint;
(*tiles)[*tileCount].joint = (long long)tileJoint;
*tileCount += 1;
if( (*tileCount) == tileCap) {
DoubleArray(tiles, &tileCap);
}
} while(true);
}
And my DoubleArray()
:
void DoubleArray(Tile **array, unsigned *cap) {
//
auto *tmp = (Tile*)realloc(*array, 2 * sizeof(Tile) );
if(tmp) {
*array = tmp;
*cap *= 2;
(*cap)--;
} else {
printf("Error allocating memory.\n");
}
}
Running the program seems fine, no errors shown and the results seem to be correct. For example:
360 217
0.1 0.0
0.2 0.0
0.3 0.0
0.4 0.0
0.6 0.0
0.8 0.0
1.2 0.0
2.4 0.0
4.1 0.0
8.2 0.0
12.3 0.0
16.4 0.0
24.6 0.0
32.8 0.0
49.2 0.0
Valgrind at 12.3 0
prints Invalid write of size 8
. So it seems to me that I'm reallocating the memory incorrectly. But if I am, why are the values loaded normally if I print them out? In other words, all inputs load into the array correctly.
So what am I doing incorrectly? Using memset
? Not free
ing correctly?