Home > Enterprise >  Debug assertion failed error on using class function C Visual Studio
Debug assertion failed error on using class function C Visual Studio

Time:12-27

I'm new to C

Code:

#include <iostream> 
#include <string> 
#include <fstream>

#include <windows.h>


class spawnTools {
    
private:
    void specTools(std::string toolname) {

    }
    void normTools(std::string toolname) {

    }
public:
    std::string toolList =
    { "regedit", "cmd" };
    std::string toolListAdmin =
    { "regedit", "cmd" };
    void initToolSet(int xadmin) {
        if (xadmin == TRUE) {

        }
        else if (xadmin == FALSE) {

        }
        else {
            MessageBox(NULL, L"SYSTEM ERROR: Incorrect input into xadmin", L"Error", MB_OK | MB_ICONERROR);
        }
    }
};

int main() {
    spawnTools st;
    st.initToolSet(TRUE); <----- Exception thrown here
}

I have set up a class with 2 public strings and 1 public function. The private functions will be filled in later in the development (just so you know I'm not hiding any code).

I'm getting an Debug Assertion error that says I have a transposed pointer range; it's not like this question as I'm using std::strings, not a vector char.

And anyway the exception is thrown on the usage of the public function, not the std::strings.

I have tried using ' commas on the std::strings instead of the normal " commas, but that throws another error, so that doesn't work.

I have tried using struct in case it's to do with class. No luck.

CodePudding user response:

You cannot initialize a std::string with two strings that way. The C strings "regedit" and "cmd" are being passed to a constructor that is normally used to pass start and end iterators of the string you want to initialize it with. This results in it attempting to initialize the string with the the address of "regedit" as the start iterator (address) of the string and the address of "cmd" as the end iterator (address) of the string. The assert you are getting is because the address of "cmd" is lower than "regedit".

Chances are you're going to want a std::array<std::string, 2> or std::vector<std::string> or even a naked std::string[2] array to hold them.

#include <string> 
#include <array>
#include <windows.h>

class spawnTools
{
private:
    void specTools(std::string toolname) {}
    void normTools(std::string toolname) {}

public:

    std::array<std::string, 2> toolList{ "regedit", "cmd" };
    std::array<std::string, 2> toolListAdmin{ "regedit", "cmd" };

    void initToolSet(int xadmin) {
        if (xadmin == TRUE) {}
        else if (xadmin == FALSE) {}
        else {
            MessageBox(
                NULL,
                L"SYSTEM ERROR: Incorrect input into xadmin",
                L"Error",
                MB_OK | MB_ICONERROR);
        }
    }
};

int main() {
    spawnTools st;
    st.initToolSet(TRUE);
}
  • Related