c++ - Windows 7 64 位 C++ malloc 失败

标签 c++ malloc windows-7-x64

我有一个小型 c++ 程序,无法使用 malloc 分配超过 2880 的内存。声明:

void* tmpptr = malloc(2881);

崩溃,同时

void* tmpptr = malloc(2880);

。每次!

我正在使用 MinGW 并进行编译

g++ -std=c++0x -pedantic -Wall -Wextra -g -D_GLIBCXX_DEBUG -static-libgcc -static-libstdc++

我知道在 C++ 中不鼓励使用 malloc,无论如何我都计划重写它,但我仍然想知道为什么这不起作用。当我用 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;,结果相同。但; for 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++ 内存分配重写代码。

关于c++ - Windows 7 64 位 C++ malloc 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15659983/

相关文章:

c - 如何避免 realloc 溢出?

C malloc/free + fgets 性能

机器人 4.2.2 : cannot see device through usb

.net - 为什么有时用十六进制字符填充进程镜像名称?

apache - Tomcat (win7) 缺少 JRE_HOME 变量

c++ - 如何在 Qt Creator 中调试 libtool 可执行文件?

c++ - 是否可以指定按位操作的返回类型?

c - 无法分配内存

C++ 仅使用矩阵按深度排序。可能的?

c++ - 如何增加fps opencv多相机设置