NeeRaX
NeeRaX

Reputation: 25

I get an error "Exception Thrown (challengeCodeAcademy.exe has triggered a breakpoint.)" whenever i run in debug mode

I already looked with a debugger and i get this error when it leaves the main() function. Here's my Code:

#include <iostream>

char * trim(const char * _str) {
    char * newString = new char;

    for (int i = 0; i < 10; i++) {
        newString[i] = _str[i];
    }
    newString[10] = '\0';

    return newString;
}

int main() {
    std::cout << trim("This is a test");
    return 0;
}

Thanks for your help.

Upvotes: 0

Views: 54

Answers (1)

pm100
pm100

Reputation: 50210

you error is this

#include <iostream>

char * trim(const char * _str) {
    char * newString = new char; <<<<==== you allocate one character

    for (int i = 0; i < 10; i++) {
        newString[i] = _str[i]; <<<<=== but try to write a whole string
    }
    newString[10] = '\0';

    return newString;
}

int main() {
    std::cout << trim("This is a test");
    return 0;
}

not sure what you are trying to do but this will work

#include <iostream>

char * trim(const char * _str) {
    char * newString = new char[strlen(_str) + 1];

    for (int i = 0; i < 10; i++) {
        newString[i] = _str[i];
    }
    newString[10] = '\0';

    return newString;
}

int main() {
    std::cout << trim("This is a test");
    return 0;
}

really you should use

  • std::string for strings in a c++ program
  • std::vector for arrays of things created on the fly

Upvotes: 1

Related Questions