C ++ - binary file for segmentation error reading

I had a problem when I try to read char* professeur in a binary file, it fails giving me a segmentation error in the read() function. Which is strange that for all other load functions in other classes for reading char* members work just fine, but for this, even if professeur is spelled correctly, I have a seg error.

So here is the code:

Cours.h

 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> using namespace std; #include "Liste.h" #include "Event.h" #include "Professeur.h" class Cours: public Event { private: char* professeur; Liste<int> groupes; public: void save(ofstream&) const; void load(ifstream&); }; 

Cours.cpp

 void Cours::save(ofstream& o) const { int n=strlen(professeur); char buff[60], *buff2; o.write((char *)&n, sizeof(int)); strcpy(buff, getProfesseur()); o.write(buff, n+1); groupes.save(o); Event::save(o); } void Cours::load(ifstream& i) { int n; char buff[60]; i.read((char *)&n, sizeof(int)); cout<<"n: "<<n<<endl; if(i.read(buff, n+1))//seg fault { strcpy(professeur, buff); cout<<"prof: "<<professeur<<endl; } else cout<<"erreur read prof cours"<<endl; groupes.load(i); Event::load(i); } 
+5
source share
2 answers

n Make sure that it does not exceed the buffer.

In save() :

 int n=strlen(professeur); 

n should be no more than 59 here - you need to check.

In load() :

 i.read((char *)&n, sizeof(int)); 

It is better to check n (max. 59).

also:

 int n=strlen(professeur); char buff[60], *buff2; o.write((char *)&n, sizeof(int)); strcpy(buff, getProfesseur()); o.write(buff, n+1); 

Two different values ​​are used to write data: strlen(professeur) , and then getProfesseur() .

You also do not allocate memory for professeur (at least not in the code shown). Thus strcpy(professeur, buff); in load() doesn't work either.

You can also change:

 private: char* professeur; 

to

 private: char professeur[60]; 

Thus, you should not have allocate and deallocate memory yourself.

And make sure all lines have zero termination.

Of course, if the exercise allows this, you can use string ( string professeur; ) instead, and the data stream in and using << and >> .

+3
source

First you read the length of the name. Allocat, how much char , since the name is long +1 for /0 , the right to the target. Read from the file to the target and add \0 to the end:

 void Cours::load(ifstream& i) { int n; i.read((char *)&n, sizeof(int)); cout<<"n: "<<n<<endl; if ( n <= 0 ) return; professeur = new char[n+1]; // allocate professeur if ( i.read( professeur, n ) ) // read directly to professeur { professeur[ n ] = Β΄\0`; // write \0 at end of name cout<<"prof: "<<professeur<<endl; } else { delete [] professeur; professeur = nullptr; cout<<"erreur read prof cours"<<endl; } groupes.load(i); Event::load(i); } 
+2
source

Source: https://habr.com/ru/post/1240281/


All Articles