Windows 7 64位C++ malloc失败
我有一个小的C++程序未能分配超过2880与malloc
。声明:Windows 7 64位C++ malloc失败
void* tmpptr = malloc(2881);
崩溃,而
void* tmpptr = malloc(2880);
不不。每次!
我使用MinGW和与
g++ -std=c++0x -pedantic -Wall -Wextra -g -D_GLIBCXX_DEBUG -static-libgcc -static-libstdc++
我知道,使用的malloc
在C被劝阻++和我打算无论如何要改写这个编制,但我还是想知道这是为什么不工作。当我用gcc编译它时,相同的代码一直在工作。
更新: 这是主函数调用:
image * img = readPPM("pic/pic.ppm");
bw_image * sky = skyline(img, ref);
cont * lin = contour(sky, 0); // <-- chash
...
和函数开头:
#include <cstdlib>
cont * contour(const bw_image * img, const char wrap) {
int test = 2880;
void* ptr1 = malloc(test);
void* ptr2 = malloc(test);
...
现在第一malloc
工作,但没有第二个。如果我更改test = 1440;
,结果相同。但;对于test = 140;
已经是第一个malloc
将会失败。
我试过的代码作为独立的:
int main(int argc, char *argv[]) {
int size = 2881;
void* tmpptr;
printf("Allocating, %d\n", size);
tmpptr = malloc(size);
printf("Allocated %d bytes successfully\n", size);
}
和它的作品没有问题,所以它似乎有什么东西在main
这样做。
rem_artifacts
这个样子的
void rem_artifacts(bw_image * sky) {
for (int y = 0; y < sky->y; ++y) for (int x = 0; x < sky->x; ++x) {
int xp = x - 1, xn = x + 1;
if (xp < 0) xp = sky->x - 1;
if (xn == sky->x) xn = 0;
int c = sky->data[x][y]; // this is wrong
if (
(y == 0 || sky->data[x][y-1] != c) && // and this
(y == sky->y-1 || sky->data[x][y+1] != c) && // and this
sky->data[xp][y] != c && // and this
sky->data[xn][y] !=c // and this
) sky->data[x][y] = !c; // and this
}
}
bw_image * skyline(const image * img, const image * ref) {
double tilt = 114.0 - 90.0;
double pi = 3.14159265358979323846;
double chang = 360.0/2.0/pi;
//double sint = sin(tilt/chang);
//double cost = cos(tilt/chang);
bw_image * sky = (bw_image*)malloc(sizeof(bw_image));
sky->x = img->x;
sky->y = img->y; //
double cos30 = sqrt(3)/2;
int lim0 = (int)((double)(img->y)/2.0 + (double)(img->x) * tan(tilt/chang) * cos30);
sky->data = (char**)malloc(sizeof(char*) * sky->y);
for (int y = 0; y < sky->y; ++y) {
sky->data[y] = (char*)malloc(sizeof(char) * sky->x);
for (int x = 0; x < sky->x; ++x)
sky->data[y][x] = !(y < lim0 && colour_dist_sq(img->data[y][x], ref->data[y][x]) < 5000.0);
}
rem_artifacts(sky);
return sky;
}
谢谢大家,
事实证明,我在写分配的内存(有点x和y的混乱)之外。奇怪的是,该计划一直工作到现在(几个月24/7),并做我一直期待的。它可以解释一些我无法解释的奇怪的东西。
现在我会反正用标准的C++内存分配来重写代码。
它看起来对我来说,你的堆在你的程序得到破坏别的地方(可能是在在main
那个大循环。你可以做的第一件事就是开始打开警告-Wall
和-Wnon-virtual-dtor
在最低限度,然后修复它们。
如果你有机会到Linux最好的办法是下运行Valgrind的这一点,并惊讶,因为它会告诉你到底在那里你覆盖内存。
如果您有权访问Windows上的Purify($$$),也可以帮助您。还有内存检查malloc库可用,您可以使用。
如果没有这些工具可用,您将不得不自己诊断,试图删除代码段,看看它是否仍然崩溃。
标志'-Wall'和'-Wnon-virtual-dtor'不会警告任何事情(除了未使用的变量)。将尝试在debian(但我想我不会有同样的问题)。无论如何,我最终需要它在Windows中运行。 – petter 2013-03-27 14:54:43
如果我冒昧猜测,这是你没有正确分配sky->data
或其子指针。
这在两个步骤来完成:
-
首先分配
sky->data
:sky->data = new char*[some_x_size];
-
然后,你必须单独分配所有子阵列:
for (int x = 0; x < some_x_size; x++) sky->data[x] = new char[some_y_size];
Yo你当然可以使用malloc
而不是new
。
当释放数据时,可以以相反的方式进行:首先释放循环中的每个子数组,然后是主数组。
gcc和mingw会是什么版本? – scones 2013-03-27 13:27:40
在其他地方看起来像未定义的行为。 – chris 2013-03-27 13:27:51
什么机器? – 4pie0 2013-03-27 13:27:58