Hey guys, so I'm new with working with random binary files, and I have a couple of questions of why certain things work...or at least look like they are working:
I have a class with a char* pointer stored inside of it, I also have a constructor that takes in a string (of any size) from the user. I then simply store this string into the char *. Once the string is stored in the char *. I reinterpret the instance, and I store the information into the random binary file. Everything works.
Question: Random files must know the size of the object that is being stored inside of it, so why when I enter strings of different sizes into the file, it appears to still be working. for example this is an example of the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
//This is just a quick example of the code I'm using to give a visual of what
//I'm trying to explain, my code works, this I just wrote,so it may or may not
class info{
private:
char *phrase;
public:
info(string n ="unknown"){
phrase = new char[n.size()+1];
phrase[n.size()] = '\0';
memcpy(phrase,n.c_str(),n.size());
}
void setPhrase(string n){
phrase = new char[n.size()+1];
phrase[n.size()]='\0';
memcpy(phrase,n.c_str(),n.size());
}
string getPhrase(){return phrase;};
};
int main(){
info objOne("abc"),objTwo("laksdflkjdsalf"),objETC(...);
//some code
fileVariable.write(reinterpret_cast<const char*>(&objOne),sizeof(info));
fileVariable.write(reinterpret_cast<const char*>(&objTwo),sizeof(info));
fileVariable.write(reinterpret_cast<const char*>(&objETC),sizeof(info));
}
|
my point is, lets just say for example the object ETC, was some long string, this would still work for me. My question is, I don't believe each object is the same size because I allocate memory for the char pointer in the constructor.
Should I not do this just to be safe, and just use a char array instead of a pointer?
(Even tho I would have set a pre-defined size for the string)
or is something happening in the back to prevent this from not working?
Thanks