Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ giving me basic_string::_S_construct null not valid error after I run my program

Tags:

c++

I am a newbie to C++ and I've tried to write a simple string reverse program. When I compile it, everything is OK, but when I run it, I get the following error:

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_S_construct null not valid
Aborted (core dumped)

What I am doing wrong? Here is my code.

#include <iostream>
using namespace std;

string reverse_string(char* argv[], int i);

int main(int argc, char* argv[])
{
    for (int i = 0; i < argc; i++)
    {
        cout << reverse_string(argv, i) << endl;
    }
    return 0;
}

string reverse_string(char* argv[], int i)
{
    string arg = argv[i + 1];
    string output;
    int length = arg.length();
    for (int index = 1; index <= length; index++)
    {
        output += arg[length-index];
    }
    return output;
}
like image 756
JadedTuna Avatar asked Jan 29 '26 11:01

JadedTuna


2 Answers

This: argv[i + 1] in the construction of your reversed string should be argv[i] and the main loop should be for (i=1; i<argc; ++i)

And there are simpler ways to reverse a string:

std::string reverse_string(char* argv[], int i)
{
    std::string arg = argv[i];
    return std::string(arg.rbegin(), arg.rend());
}
like image 185
WhozCraig Avatar answered Jan 31 '26 00:01

WhozCraig


This error message

terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid

means that you are trying to call constructor of std::string passing as argument pointer NULL. The problem is that *(argv + argc) is NULL pointer.

Also take into account that you must include header <string>

As for the reverse function then it can be written much simpler then that of you. First of all it could have only one parameter of type const char *

For example

#include <iostream>
#include <string>

std::string reverse_string( const char* s );

int main(int argc, char* argv[])
{
    for (int i = 1; i < argc; i++)
    {
        std::cout << argv[i] << " -> " << reverse_string( argv[i] ) << std::endl;
    }
    return 0;
}

std::string reverse_string( const char* s )
{
    std::string arg( s );
    return std::string( arg.rbegin(), arg.rend() );
}
like image 29
Vlad from Moscow Avatar answered Jan 31 '26 01:01

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!