C++, Getting EXC_BAD_ACESS?

  c++, malloc, new-operator, pointers

I have the following function (which I can’t change):

int _parseCommandLine(const char *cmd_line, char **args) {
    FUNC_ENTRY()
    int i = 0;
    std::istringstream iss(_trim(string(cmd_line)).c_str());
    for (std::string s; iss >> s;) {
        args[i] = (char *) malloc(s.length() + 1);
        memset(args[i], 0, s.length() + 1);
        strcpy(args[i], s.c_str());
        args[++i] = NULL;
    }
    return i;

    FUNC_EXIT()
}

and I have:

Command::Command(const char *cmd_line) {
    cmd=new char[80];
    strcpy(cmd,cmd_line);
    char **args = new char* [COMMAND_MAX_ARGS];
    num_of_args=_parseCommandLine(cmd_line, args);
}

void CatCommand::execute() {
    if (this->num_of_args==0)
    {
        PROMPT = "smash> ";
    }
    else
    {
        PROMPT = args[0];
    }
}


void SmallShell::executeCommand(const char *cmd_line) {
    Command *cmd = CreateCommand(cmd_line);
    cmd->execute();
}

But the program ends like this:

EXC_BAD_ACESS

on PROMPT = args[0];

what is causing this bug? I have no clue on how to fix it

Source: Windows Questions C++

LEAVE A COMMENT