Tyranitar
Tyranitar

Reputation: 37

C++ Program crash when doing string assign

I have a weird problem, this is my code :

test.h

#ifndef _test_
#define _test_
#include <iostream>
#include <string>
class Test {
public:
    Test();
    ~Test();
    void addName(std::string _Name);
private:
    std::string Name;
};
#endif // _test_ 

test.cpp

#include "test.h"
Test::Test() {}
Test::~Test() {}
void Test::addName(std::string _Name) {
    std::cout << _Name << std::endl;
    Name = _Name;
    std::cout << _Name << std::endl;
}

main.cpp

#include "test.h"
int main(int argc, char* argv[]) {
    Test* project;
    project->addName("abc");
    return 0;
}

Results :

abc

The program has unexpectedly finished.

Upvotes: 0

Views: 1225

Answers (2)

MikeCAT
MikeCAT

Reputation: 75062

The pointer project is default-initialized and has indeterminate value, so dereferencing it has a big chance to cause abnromal termination of the program.

Try creating an object and assigning it before dereferencing like this:

#include "test.h"
int main(int argc, char* argv[]) {
    Test* project = new Test;
    project->addName("abc");
    delete project;
    return 0;
}

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409442

That's because you have a pointer to a Test object, but it doesn't actually point anywhere. That leads to undefined behavior when you try to dereference the pointer.

Declare the object as an actual object, not a pointer:

Test project;
project.addName("abc");

Upvotes: 6

Related Questions