I had a weird behavior of a piece code today under windows
std::vector<std::string> getMACs() {
std::vector<std::string> macs;
for(/*something*/) {
char buffer[100];
sprintf_s(buffer, size, "get the mac address here");
std::string s = "";
s.append(buffer);
printf("mac=%s\n", s.c_str(); //print the mac address correctly
macs.push_back(s);
}
return macs;
}
int main(int, char**) {
std::vector<std::string> macs = getMACs();
for (size_t i = 0; i < mac.size(); i++) {
printf("mac=%s\n", macs[i]); //prints garbage
}
}
although the mac address inside the function has been printed correctly, in the main it prints garbage, the only explanation I have, that the macs vector is full of garbage strings, but how can this happen; a call to string.append(const char*), though passes by reference, the push_back() function should call the copy constructor of string, and so it should not point any more to a string reference that will turn into garbage after leaving the scope, right?
Because
macs[i]is of typestd::string, andprintfdoesn’t know how to handle that. Try this:Or this:
Type safety, FTW