I am trying to run a simple program in C++ which basically counts the amount of symbols using the length()
function from the <string>
library of C++.
Here’s my custom function:
#include <iostream>
#include <string>
using namespace std;
string TrimTextFunction() {
string Text = "Hello I am your program!";
cout << "String size is: " << Text.length();
return 0;
}
Then, I simply run this custom function inside main()
through the debugger in Visual Studio:
int main()
{
cout << TrimTextFunction();
}
Eventually, I get this error code:
Exception thrown at 0x00007FFE67837A41 (ucrtbased.dll)
Then, it redirects me to the inner file called xstring
showing the error itself.
Without the debugger, the code returns the value I need.
But when I run the same code inside main()
using the same debugger (or without), it has no error whatsoever.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string Text = "Hello I am your program!";
cout << "String size is: " << Text.length();
}
It seems like I am missing something about custom functions, particularly when I debug something.
Why does the main()
function allow me to get a result that I need without error, and a custom function doesn’t?
I have used a custom function and I need to expect a result of a string
that returns the length of a string
variable, which is 24.
2
Answers
Your function is defined as
In this case using
0
to construct astd::string
is invoking the constructorNote that as of C++23 this constructor is declared deleted so this wouldn’t even compile
If you just want your helper function to output to stdout then it does not need to return anything, and therefore the return type would be
void
and you can omit areturn
statementLets make the example simpler. The version with all code in main is
You want to place the
42
inside a function. The function should return that value. That would be:But what you did instead is something along the line of this:
You have to decide: Is the function printing the value on the screen. Or is the function returning the value so that
main
can print it. You could also make both, the function print it and letmain
print it. However, your code is somewhere in between.Here
You let
TimeTextFunction
print the result and return some unrelated 0. Unfortunatelystd::string
has a constructor that can be called with a literal0
, but it invokes undefined behavior when you do so, because it expects a pointer to nullterminated string, while0
converts to anullptr
.main
on the other hand looks like the function returns the restul to be printed, it uses the returned result to print it.The solution is, as mentioned above, to not confuse printing on the screen with returning from a function. Decide whether the function or
main
or both should print it and when you declare the function to return astd::string
make sure it returns a properstd::string
(I suppose you actually want to return asize_t
, the length of the string).