string - Strncpy Causing Segmentation Fault c++ -
i have c++ program reads text file , converts text file string. then, converts string character array using strncpy. have seen stackoverflow question on strncpy , taken necessary precautions in order avoid issues causes when creating array. please explain why still causes stack error.
#include <iostream> #include <string.h> #include <random> #include <fstream> #include <istream> #include <sstream> #include <stdio.h> using namespace std; int main() { //open stream reader ifstream fin; //opens text file in stream reader fin.open("songlyrics.txt"); //will used aggregate characters in text file string song; //used pointer when reading each character in text file char ch; //while end of file not reached while(!fin.eof()) { //get character file , add song string fin.get(ch); song += ch; } //close file fin.close(); //make character array called lyrics_ length of length of song char lyrics_[song.length()]; //use strncpy convert song char array, lyrics_ strncpy(lyrics_, song.c_str(), sizeof(lyrics_)); //avoid segmentation fault lyrics_[sizeof(lyrics_) - 1] = 0; cout<<lyrics_; return 0; }
this:
char lyrics_[song.length()]; // ^^^^^^^^^^^^^ // not compile-time constant
is variable-length array, , not standard c++.
also, don't need convert std::string
character array. kind of is:
char* lyrics = &song[0]; // assuming don't append song in future
if want separate character buffer, you'll have allocate dynamically:
char* lyrics = new char[song.length() + 1]; memcpy(lyrics, song.c_str(), song.length() + 1); // copy null terminator delete [] lyrics; // don't forget
Comments
Post a Comment