Reputation: 3
well i'm hardly trying to figure out why a segmentation fault occurs in the following code in one of my classes, the function is called once,
void fileTransfer::createFile(){
std::ofstream fout;
fout.open("th.txt", std::ios::binary | std::ios::out);
char *toSend = new char();
for (int i=0;i<totalSize_;i++) {
toSend[i]=totalData_.front();
totalData_.pop_front();
}
std::cout<<"stage 1"<< std::endl;
fout.write(toSend, totalSize_);
fout.flush();
std::cout<<"stage 2"<< std::endl;
fout.close();
std::cout<<"stage 3"<< std::endl;
}
and i'm getting:
stage 1
stage 2
Segmentation fault (core dumped)
any ideas why is this happening?
Upvotes: 0
Views: 2541
Reputation:
This:
char *toSend = new char();
creates a pointer that points to a single dynamically allocated character, which you then treat as if it were an array of multiple characters. You could use:
char *toSend = new char[totalSize];
or similar, but really you want to use a std::vector <char>
or a std::string
.
Upvotes: 4