Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access violation error while appending time to string in c++

Take the following code:

#inlcude <iostream>
#include <time.h>
using namespace std;

int main(int argc, char* argv[])
{
    time_t t;
    time(&t);

    string s = "file" + t;
    return 0;
}

At the line

string s = "file" + t

I get an access violation error.

If I change it to something like: #inlcude using namespace std;

int main(int argc, char* argv[])
{
    time_t t;
    time(&t);
    int x = t;

    string s = "file" + x;
    return 0;
}

I still get the same error. What is up? Surely appending an int to a string can't throw an access violation?

like image 458
Tom Avatar asked Jan 17 '23 16:01

Tom


1 Answers

"file" + t

That does not do at all what you expect. "file" is a char array. You can't add an integer to a char array. But you can add an integer to a pointer, and arrays are implicitly convertible to pointers. The value of t is probably somewhere in the billions. So the result of "file" + t is some pointer a billion or so bytes away from the char array "file". You then try to initialize a string with that pointer. It's very unlikely that you have legal access to this memory location, so you get an access violation. It's undefined behavior either way. If you would have done this:

std::string s("file");
s += t;

You would have gotten a proper compiler error. Try this instead:

std::string s("file");
s += std::to_string((long long)t);

If that function is not available to you (it's new in C++11), then you can use stringstreams:

std::ostringstream oss;
oss << "file" << t;
std::string s(oss.str());
like image 150
Benjamin Lindley Avatar answered Jan 27 '23 10:01

Benjamin Lindley