0

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.

3

2 Answers 2

6

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");
Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

3 Comments

No reason to use new here.
@crashmstr there is a need to use new here if the OP wishes to use *project. Otherwise, there is no reason to use new here if the OP changes what project is.
@johnbakers *project can be used without new like this: Test hoge; Test *project = &hoge;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.