【问题标题】:Heap Data Messed Up堆数据搞砸了
【发布时间】:2012-11-06 01:17:20
【问题描述】:

我很幸运通过阅读其他人的问题在这里找到了很多有用的答案,但这一次我完全无能为力,所以我不得不自己提出一个问题:

我尝试创建一个将卷积应用于数据系列的程序。对于具有不同长度的卷积核(=特定数字的数组)。

我通过使用float** 并在两次取消引用的变量处插入值来实现这一点。数组的数量是固定的,每个数组的长度不是固定的,所以“子数组”是通过new分配的——在CreateKernels函数中if之后。

然后,此函数将 float** 与另一个绑定为 main 结构的指针一起返回。

现在问题来了: 我用调试手表查看了内核指针的取消引用值。一切正常,所有数字在CreateKernels 返回后都符合预期(即从main 范围查看内存)。但是在main 中的下一个命令之后,我的号码完全搞砸了。 如果我尝试在后续代码中使用数据,则会出现段错误。

所以我目前的推理是: 当我使用new 创建变量时,它们应该在堆中并且应该一直留在那里直到我free[] 变量——无论如何它们不应该被限制在CreateKernels 的范围内。分配指向内核结构的指针并返回它对你们中的一些人来说可能很奇怪,但它确实有效。 所以真正弄乱我的数据的是CreatKernels之后的下一个命令。初始化 int 而不是创建 fstream 不会弄乱我的数字。但为什么呢?

这是我的操作系统内存管理出错了吗?或者这是一个愚蠢的编程错误? 我正在运行 Ubuntu 12.04-64bit 并使用 Code::Blocksg++ 进行编译(所有默认设置),两个可执行文件都给了我一个段错误。

我非常感谢任何有关此问题的提示或经验!

这是相关代码:

#include <string>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#define HW width/2
#define width1 4       // kernel width-1 (without peak)

using namespace std;

struct kernel_S
{
    const float ** ppkernel;
    const float * pnorm;
};

void BaseKernel(const int & width, float * base) // function that fills up an 1d-array of floats at the location of base
{
    for(int i=0; i<=HW-1; i++)      // fill left half as triangle
    {
        base[i] = i+1;
     }
    base[HW] = HW+1;          // add peak value
    for(int i=HW+1; i<=width; i++)   // fill right half as decreasing triangle
    {
        base[i] = width-i+1;
    }
}

kernel_S CreateKernels(const int &width) // function that creates an array of arrays (of variable length)
{
float base_kernel[width+1];    // create a full width kernel as basis
BaseKernel(width, base_kernel);

float * kernel[width+1];       // array of pointers, at each destination of a pointer a kernels is stored
float norm[width+1];           // norm of kernel

for(int j=0; j<=width; j++)    // fill up those individual kernels
{
    norm[j] = 0;
    if(j<=HW)                   // left side up to peak
    {
        kernel[j] = new float[HW+j+1]; // allocate mem to a new array to store a sub-kernel in
        for(int i=0; i<=HW+j; i++)
        {
            *(kernel[j]+i) = base_kernel[HW-j+i];  //use values from base kernel
            norm[j] += base_kernel[HW-j+i];        // update norm
        }
    }
    else if(j>=HW+1)
    {
        kernel[j] = new float[HW+width-j+2];
        for(int i=0; i<=HW+width-j; i++)
        {
            *(kernel[j]+i) = base_kernel[i];
            norm[j] += base_kernel[i]; // update norm
        }
    }
}

kernel_S result;                // create the kernel structure to be returned
result.ppkernel = (const float **) kernel;  // set the address in the structure to the address of the generated arrays
result.pnorm    = (const float *) norm; // do the same for the norm
return result;
}

int main()
{
    kernel_S kernels = CreateKernels(width1);            // Create struct of pointers to kernel data
    ifstream name_list(FILEPATH"name_list.txt", ios::in);// THIS MESSES UP THE KERNEL DATA

    // some code that would like to use kernels

    return 0;
}

【问题讨论】:

    标签: c++ pointers memory heap-memory


    【解决方案1】:

    请看

    How do I use arrays in C++?

    您返回指向本地堆栈数据(内核和规范)的指针。您应该动态分配:

    float ** kernel = new float*[width+1];       // array of pointers, at each destination of a pointer a kernels is stored
    float *norm = new float[width+1];           // norm of kernel
    

    记得用 delete[] 删除。

    不过,我建议改用 std::vector 或 std::array

    #include <string>
    #include <stdlib.h>
    #include <iostream>
    #include <fstream>
    #include <iomanip>
    #include <vector>
    #define HW width/2
    #define width1 4       // kernel width-1 (without peak)
    
    using namespace std;
    
    typedef std::vector<float> floatV;
    typedef std::vector<floatV> floatVV;
    
    struct kernel_S
    {
        floatVV kernel;
        floatV  norm;
    };
    
    floatV BaseKernel(int width)       // function that fills up an 1d-array of floats at the location of base
    {
        floatV base;
        base.resize(width + 1);
        for(int i=0; i<=HW-1; i++)     // fill left half as triangle
        {
            base[i] = i+1;
        }
        base[HW] = HW+1;               // add peak value
        for(int i=HW+1; i<=width; i++) // fill right half as decreasing triangle
        {
            base[i] = width-i+1;
        }
        return base;
    }
    
    kernel_S CreateKernels(const int &width)                   // function that creates an array of arrays (of variable length)
    {
        const floatV base_kernel = BaseKernel(width);          // create a full width kernel as basis
    
        kernel_S result;                                       // create the kernel structure to be returned
        result.kernel.resize(base_kernel.size());
        result.norm.resize(base_kernel.size());
    
        for(int j=0; j<=width; j++)                            // fill up those individual kernels
        {
            result.norm[j] = 0;
            if(j<=HW)                                          // left side up to peak
            {
                result.kernel[j].resize(HW+j+1);               // allocate mem to a new array to store a sub-kernel in
                for(int i=0; i<=HW+j; i++)
                {
                    result.kernel[j][i] = base_kernel[HW-j+i]; // use values from base kernel
                    result.norm[j] += base_kernel[HW-j+i];     // update norm
                }
            }
            else if(j>=HW+1)
            {
                result.kernel[j].resize(HW+width-j+2);
                for(int i=0; i<=HW+width-j; i++)
                {
                    result.kernel[j][i] = base_kernel[i];
                    result.norm[j] += base_kernel[i];          // update norm
                }
            }
        }
        return result;
    }
    
    int main()
    {
        kernel_S kernels = CreateKernels(width1);     // Create struct of pointers to kernel data
        ifstream name_list("name_list.txt", ios::in);
    
        // some code that would like to use kernels
    
        return 0;
    }
    

    注意如果你想让kernelnorm 在结果结构中成为const,只需将整个结构设为const:

        const kernel_S kernels = CreateKernels(width1);
    

    【讨论】:

    • 非常感谢。我只见树木不见森林,因为我给自己的错误印象是它是动态分配的,但显然只有一半是......感谢您查看我的代码!
    • 添加了使用 std::vector 的代码的演示。通常,在现代 C++ 中,每当您编写 newdelete 时,您都在做错事/过于复杂(99% 的时间)
    • @sehe:一个小分歧:我会说这更像是 99.99%。
    • @JerryCoffin 我无法让 std::nextafter(100.0, -1) 代表 :)
    • @sehe:感谢矢量演示。我仍然处于从基础级别学习 C++ 到创建有目的的代码的过渡阶段——这就是为什么我在低级别手工做很多事情的原因。但也许现在是我更多地研究库函数的时候了。顺便说一句:我注意到你整齐地对齐了我的 cmets。您是否有自动执行此操作的编辑器或 IDE?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2010-10-15
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多