Access violation error when adding time to a 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; } 

In line

 string s = "file" + t 

I get an access violation error.

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

 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's up? Surely adding an int to a string cannot cause an access violation?

+4
source share
3 answers
 "file" + t 

This does not mean what you expect. "file" is an array of char. You cannot add an integer to a char array. But you can add an integer to the pointer, and arrays are implicitly converted to pointers. The value of t is probably somewhere in the billions. Thus, the result of "file" + t is some pointer in a billion or so bytes from the char "file" array. Then you try to initialize the string with a pointer. It is very unlikely that you have legitimate access to this memory location, so you get an access violation. This behavior is undefined anyway. If you did this:

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

You would get the correct compiler error. Try instead:

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

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

 std::ostringstream oss; oss << "file" << t; std::string s(oss.str()); 
+5
source

This is not a standard way to add an integer to a string. C ++ represents a string as a pointer to an array of characters. By adding an integer to it, you actually increase the pointer to a block of memory that may not belong to you. Learn the use of sprintf () for what you need.

+2
source

The problem is that your lines are not lines.

You need to remember that string literals (forms "foo" not of type std::string , but const char* (in fact they are of type const char[N] , but for our purposes we can consider them pointers).

So, when you write code like this:

 std::string foo = "bar" + 42 

then the types are involved as follows:

 std::string = const char* + int 

In other words, your code adds an integer to the pointer, and then the resulting char pointer is saved as a string.

Note that adding an integer to a pointer is a simple arithmetic of pointers, so the compiler will not complain.

If we do this:

 std::string foo = std::string("bar") + 42 

then we create the correct line, and then try to add 42 to it. This is not defined, so we get a compiler error (which is at least better than doing it silently incorrectly).

The correct solution is to use a stream, as shown in one of the other answers:

 std::ostringstream os("file"); os << x; std::string s = os.str(); 
+2
source

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


All Articles