班上:
class Tile {
public:
long long size, joint;
};
我的主要有:
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.
}
这里有问题的功能是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);
}
而我的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");
}
}
运行程序似乎很好,没有显示错误,结果似乎是正确的。例如:
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 在12.3 0
打印Invalid write of size 8
。所以在我看来,我错误地重新分配了内存。但是如果我是,如果我打印出来,为什么这些值会正常加载?换句话说,所有输入都正确加载到数组中。
那么我做错了什么?使用memset
? 不free
正确?
您正在错误地重新分配内存。该接口std::malloc
,std::calloc
并且std::realloc
有些不一致,关于大小来分配的混乱。std::malloc
并std::realloc
采用单个大小参数,它应该是对象数乘以它们的大小。std::calloc
有两个参数,一个是对象的数量,一个是一个对象的大小。
你在打电话
auto *tmp = (Tile*)realloc(*array, 2 * sizeof(Tile) );
这(重新)为两个瓷砖分配空间。你应该写一些类似的东西
*cap *= 2;
auto *tmp = (Tile*)realloc(*array, *cap * sizeof(Tile) );
额外的内存将未初始化,因此您可能需要将 memset() 设为 0。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句