我已經幸運地發現了很多在這裏有用的答案通過閱讀別人的問題,但這次我徹底無奈,所以我要提出一個問題自己:堆數據搞砸
我嘗試創建一個程序,對數據序列應用卷積。對於需要具有不同長度的卷積內核(=特定數字的數組)。
我通過使用float**
並在兩個解除引用的變量處插入值來實現此目的。陣列的數量是固定的,每個陣列的長度不是,所以通過使用new
—在功能CreateKernels
中的if
之後分配「子陣列」。
該函數然後將float**
與另一個綁定爲結構的指針一起返回給main。
現在,這裏是問題: 我看着我的調試手錶指針內核的取消引用的值。一切正常,CreateKernels
返回後(即從main
範圍查看內存)後,所有數字都符合預期。但在main
下一個命令後,我的號碼被完全擰緊。 如果我嘗試在後續代碼中使用數據,則會出現段錯誤。
那麼我現在的理由是: 因爲我用new
創建他們應該是在堆和應該呆在那裏,直到我free[]
變量—在他們不應該侷限於任何率變量範圍爲CreateKernels
。指向內核結構的指針並返回它對於你們中的一些人來說可能很奇怪,但它起作用。 那麼究竟是什麼讓我的數據混亂是CreatKernels
之後的下一個命令。初始化一個int
而不是創建一個fstream
不會弄亂我的數字。但爲什麼?
這是我的操作系統內存管理錯誤?或者這是一個愚蠢的編程錯誤? 我正在運行Ubuntu 12.04-64bit並使用Code::Blocks
和g++
進行編譯(所有默認設置),並且這兩個可執行文件都給了我一個段錯誤。
我真的很感謝這個問題的任何暗示或經驗!
這是相關代碼:
#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;
}
非常感謝。我錯過了樹林,因爲我錯誤地認爲它是動態分配的,但顯然只有一半是......謝謝你看我的代碼! –
添加了代碼與std :: vector代碼相似的演示。作爲一個規則,在現代C++中,無論何時編寫'new''或'delete',你都會做錯事情/過度複雜化(99%的時間) – sehe
@sehe:一個小小的分歧:我會說它更像99.99% 。 –