[英]segmentation fault at end of the program
我有點問題。 我的程序在main中返回零時引發分段錯誤。
主要功能如下:
int main(int argc, char* argv[]){
ifstream fs("test.dat", ios::binary);
cSendStream sendstr(&fs,20);
char *zomg=sendstr.data();
//zomg[20]=0;
sendstr.read(20);
cout<<"Buffer: "<<sendstr.data()<<endl;
cout<<"Remaining: "<<sendstr.dataAvailable()<<endl;
sendstr.read(2);
cout<<"Buffer: "<<zomg<<endl;
cout<<"Remaining: "<<sendstr.dataAvailable()<<endl;
sendstr.read(10);
cout<<"Buffer: "<<zomg<<endl;
cout<<"Remaining: "<<sendstr.dataAvailable()<<endl;
cout<<"end..."<<endl;
return 0;
}
注釋的zomg
部分是使程序崩潰的關鍵。 zomg
指向char[20]
。 我在那條線上的目的是設置數組的結尾,因為如果不這樣做,該流將讀取多於20個字節的數據,但它只會輸出一個不必要的符號。
有趣的是,即使我在此之間編寫了一些附加代碼並返回0,返回時也會首先引發錯誤。
就您想看cSendStream類的情況而言:
cSendStream.h:
class cSendStream{
public:
cSendStream(std::istream*, int streamsize);
int read(int);
int dataAvailable();
char* data();
private:
void shift(int);
std::istream *source;
int streamsize;
char* buffer;
};
和cSendStream.cpp:
#include "cSendStream.h"
cSendStream::cSendStream(std::istream *src, int size){
source=src;
streamsize=size;
buffer=new char[streamsize];
memset(buffer,0,streamsize);
}
int cSendStream::read(int i){
if(dataAvailable()<1 || i<=0){
return 0;
}
if(i>dataAvailable()){
i=dataAvailable()-1;
}
if(i>streamsize){
i=streamsize;
}
shift(i);
source->read(&(buffer[streamsize-i]),i);
return i;
}
int cSendStream::dataAvailable(){
int current=source->tellg();
source->seekg (0, std::ios::end);
int available = (int)(source->tellg())-current;
source->seekg (current);
return available;
}
char* cSendStream::data(){
return buffer;
}
void cSendStream::shift(int i){
char tmp[2048];
memcpy(tmp,buffer,streamsize);
memcpy(&(buffer[0]),&(tmp[i]),streamsize-i);
}
zomg [20] = 0在分配的數組末尾寫入一個,但是很難猜測為什么發生段錯誤。 我的猜測是,您的聰明編譯器正在使用alloca進行分配,並且您在返回地址上亂塗亂畫。
查看程序集(通常為-S)以查看發生了什么可能會很有趣。
您正在分配char[20]
的數組,該數組的有效索引為0-19,但是您嘗試訪問索引20。這將導致segfault。
因此,此位在此處分配了大小為20的緩沖區:
new char[streamsize]
但是,然后您嘗試達到第21個角色:
buf[20]
有段錯誤。 數組基於零,因此對於大小為20的數組,索引從0到19。
為了擴展int3的答案,如果您的數據長度為20個字符,則需要聲明一個長度為21個字符的數組,以便可以使用空終止符來“完成”。 如果這樣做了,那么您的代碼將作為zomg[20]
在數組中有效輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.