做一些C++的樂趣,並有一個問題,當我在對圖像做一些修改後加載圖像時,它給我提供了分段錯誤。我覺得我錯過了一些東西,但我不知道在哪裏。當從二進制文件加載圖像像素時發生C++分段錯誤
編輯下面是該代碼同時保存和加載功能,(假設所有必要的頭文件都包含):
int Image::save(const char* filename)
{
if(filename == NULL)
{
return 1;
}
///*
ofstream outFile(filename, ios::out | ios::binary);
if (!outFile)
{
return 1;
}
outFile.write(reinterpret_cast<char*>(&cols), sizeof(unsigned int));
outFile.write(reinterpret_cast<char*>(&rows), sizeof(unsigned int));
outFile.write(reinterpret_cast<char*>(pixels), sizeof(uint8_t) * cols * rows);
outFile.close();
return 0;
}
int Image::load(const char* filename)
{
if(filename == NULL)
{
return 1;
}
///*
ifstream inFile(filename, ios::in | ios::binary);
if (!inFile)
{
return 1;
}
**//feels like the segmentation fault is happening here**
inFile.read(reinterpret_cast<char*>(&cols), sizeof(unsigned int));
inFile.read(reinterpret_cast<char*>(&rows), sizeof(unsigned int));
inFile.read(reinterpret_cast<char*>(pixels), sizeof(uint8_t) * cols * rows);
inFile.close();
return 0;
}
編輯 這裏,我一起工作的頭文件:
class Image {
public:
unsigned int cols;
unsigned int rows;
uint8_t* pixels;
...
/* Saves the image in the file filename. In a format that can be
loaded by load(). Returns 0 on success, else a non-zero error
code. */
int save(const char* filename);
/* Load an image from the file filename, replacing the current
image size and data. The file is in a format that was saved by
save(). Returns 0 success, else a non-zero error code . */
int load(const char* filename);
};
什麼是像素? – vu1p3n0x
我認爲這可能是在你的寫功能保存。當你使用char *時,可能只允許讀取操作。這是我的第一個猜測。你能測試一下保存方法,看看你是否實現了seg故障? –
爲什麼不直接用調試器檢查它發生的位置?另外,順便提一下,行,列和像素是什麼?爲什麼他們顯然是全球性的? – KjMag