C++ Program crash when doing string assign - c++

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.

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");

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

Related

Why does this variable have different values in different source files?

I have the following code:
main.cpp
#include "Test.h"
int main() {
Create();
}
Test.h
#pragma once
#include <iostream>
#include "Function.h"
class Test {
public:
Test();
};
extern Test* g_pTest;
inline void Create() {
g_pTest = new Test;
std::cout << "On Test.h: " << std::endl;
PrintAddr();
}
Test.cpp
#include "Test.h"
Test* g_pTest = nullptr;
Test::Test() {
std::cout << "On Test.cpp:" << std::endl;
PrintAddr();
}
Function.h
#pragma once
void PrintAddr();
Function.cpp
#include "Function.h"
#include "Test.h"
void PrintAddr() {
std::cout << "g_pTest address is " << g_pTest << std::endl;
}
When I run it, I get the following output:
On Test.cpp:
g_pTest address is 0000000000000000
On Test.h:
g_pTest address is 000002008A5EAE40
I thought that a extern variable was supposed to have the same value anywhere on the code, so why doesn't it? I've tried to run the same code, but instead of the Test class, I just have a function:
Test.h
#pragma once
#include <iostream>
#include "Function.h"
void Test();
extern int* g_pTest;
inline void Create() {
g_pTest = new int;
Test();
std::cout << "On Test.h: " << std::endl;
PrintAddr();
}
Test.cpp
#include "Test.h"
int* g_pTest = nullptr;
void Test() {
std::cout << "On Test.cpp:" << std::endl;
PrintAddr();
}
And it somehow works if it is done this way, I don't understand the logic...
What am I doing wrong here? What can I do in order to use a class and have access to the same extern variable in any code file?
int main() {
Create();
}
main calls Create(), which does this:
g_pTest = new Test;
Test gets newed first. g_pTest gets assigned after Test's constructor finishes and the object is constructed.
Test's constructor calls PrintAddr which prints the value of g_pTest because it is still nullptr:
Test* g_pTest = nullptr;
This remains the case until after Test finishes constructing.
Only after the constructor wraps up its business the pointer to the new object gets assigned to g_pTest, and then the 2nd call to printAddr (from Create) prints the value of the pointer, which is now pointing to the new object.

In function int main(): class name was not declared in this scope

Im using vscode and im new to c++. I learned how to create a header file link to its cpp and use it to main.cpp. The only problem bugs me out is why it causes an error this is my simple code.
Name.h
#include <iostream>
#include <string>
class myname
{
public:
void setname(std::string name);
void prname();
private:
std::string Name;
};
Name.cpp
#include "Name.h"
void myname::setname(std::string name)
{
Name = name;
}
void myname::prname()
{
std::cout<<"Hello :"<<Name<<std::endl;
}
Maiin.cpp
#include <iostream>
#include <string>
#include "Name.h"
using std::cout;
using std::string;
using std::endl;
int main()
{
myname Epoy; // IN FUNCTION INT MAIN: ERROR myname was not declared in this scope
Epoy.setname("Jomar"); //note myname <-rename "BUT THIS IS NOT THE ERROR CAUSE THIS JUST HAPPEN BECAUSE OF THE ERROR ABOVE "
Epoy.prname();
return 0;
}
also i tried so many method i even compiled this by using g++ Maiin.cpp Name.cpp - o Maiin
Still didnt work
Edit: Community want me to add more details.
What I asked was, have you write header guards in your header file: #ifndef Name_H, #define Name_H, #endif ? Since you use vscode you have to done it manually.
Like this:
#ifndef Name_H
#define Name_H
#include <iostream>
#include <string>
class myname
{
public:
void setname(std::string name);
void prname();
private:
std::string Name;
};
#endif
you missing a C++ constructor:
class Foo {
public:
Foo() { /* your init code */ } // <-- this is a std. C++ constructor
~Foo() { /* your clean-up code */ } // <-- this is a std. C++ de-structor
};
int main(int argc, char **argv) {
Foo bar; // here, you don't need the: ( ) object on heap !
}

c++ how to correctly reference a class attribute's value

I don't know exactly why this is happening but it seems that the code is "losing" the value of an attribute. I got a class defined as (in Foo.h):
#ifndef FOO_H
#define FOO_H
using namespace std;
#include <string>
class Foo{
public:
Foo(short int id);
void Foo::DoSomething(std::string someMsg);
private:
short int id;
};
#endif /* FOO_H */
in the class implementation (Foo.cpp):
#include "Foo.h"
#include <iostream>
Foo::Foo(short int id) {
this->id = id;
cout << "value now: " << this->id << "\n"; // I print to be sure it was set correctly and it prints the right value
}
void Foo::DoSomething(std::string someMsg) {
cout << "Foo number: " << std::to_string(this->id) << someMsg;
// when it runs this code called by another class, it always prints 0 to this->id for all objects instantiated
}
Then, I got another class, Bar. In Bar.h I have:
#ifndef BAR_H
#define BAR_H
#include <iostream>
using namespace std;
#include <list>
#include "Foo.h"
class Bar {
public:
Bar();
void setValor(std::string valor);
void notifyAllFoos();
void Bar::registerFoo(Foo *h);
private:
std::list<Foo> foos;
};
#endif /* BAR_H */
In Bar.cpp I have:
#include "Bar.h"
void Bar::setValor(std::string valor){
// do more stuff
this->notifyAllFoos();
}
void Bar::registerFoo(Foo *h){
this->foos.push_back(*h);
}
void Bar::notifyAllFoos(){
for(std::list<Foo>::iterator it=this->foos.begin() ; it!=this->foos.end() ; it++){
it->DoSomething("myMsg");
}
}
Finally, in main.cpp:
#include <cstdlib>
#include "Bar.h"
#include "Foo.h"
using namespace std;
int main(int argc, char** argv) {
Bar *b = new Bar();
b->registerFoo(new Foo(1));
b->registerFoo(new Foo(2));
b->registerFoo(new Foo(3));
b->setValor("Value");
delete b;
return 0;
}
Basically, Bar must notify all Foos of it's list that an update of an Value occured and print a Msg. To identify each Foo I put this id but it keeps printing 0 for all.
Why is this happening? It must be something very simple I guess but I'm not used to c++. Thanks in advance.
That:
std::list<Foo> foos;
will store copies of objects from class Foo.
You need to store pointers, like this:
std::list<Foo*> foos;
PS: Never forget to delete for every new, when you are done.
I did take your code and put it into one file, added includes and using at the top and commented out declaration of Bar constructor.
#include <string>
#include <iostream>
using namespace std;
class Foo{
public:
Foo(short int id);
void Foo::DoSomething(std::string someMsg);
private:
short int id;
};
Foo::Foo(short int id) {
this->id = id;
cout << "value now: " << this->id << "\n"; // I print to be sure it was set correctly and it prints the right value
}
void Foo::DoSomething(std::string someMsg) {
cout << "Foo number: " << std::to_string(this->id) << someMsg;
// when it runs this code called by another class, it always prints 0 to this->id for all objects instantiated
}
#include <list>
class Bar {
public:
//Bar();
void setValor(std::string valor);
void notifyAllFoos();
void Bar::registerFoo(Foo *h);
private:
std::list<Foo> foos;
};
void Bar::setValor(std::string valor){
// do more stuff
this->notifyAllFoos();
}
void Bar::registerFoo(Foo *h){
this->foos.push_back(*h);
}
void Bar::notifyAllFoos(){
for(std::list<Foo>::iterator it=this->foos.begin() ; it!=this->foos.end() ; it++){
it->DoSomething("myMsg");
}
}
int main () {
Bar *b = new Bar();
b->registerFoo(new Foo(1));
b->registerFoo(new Foo(2));
b->registerFoo(new Foo(3));
b->setValor("Value");
}
It gives me following output
value now: 1
value now: 2
value now: 3
Foo number: 1myMsgFoo number: 2myMsgFoo number: 3myMsg
Is it what you are looking for?

SDL2 Thread not working inside class

I am trying to create a input handler using multi threading with the SDL2 Library; however, when I try to put a thread in a class it won't compile and gives me this error...
error: cannot convert 'inputHandlerClass::getInput' from type 'int (inputHandlerClass::)(void*)' to type 'SDL_ThreadFunction {aka int (*)(void*)}'
I'm pretty sure that its the way I am passing the function name (fn) to the SDL_CreateThread function.
This is the source.cpp file
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <SDL_thread.h>
#include <SDL_mixer.h>
#include "..\include\gameClass.hpp"
#include "..\include\inputHandlerClass.hpp"
int main(int argc, char *argv[]){
inputHandlerClass inputHandler;
inputHandler.startThread();
std::cout << "hello world";
return 0;
}
This is the inputHandlerClass.hpp
#include <SDL_thread.h>
#include <iostream>
class inputHandlerClass{
private:
SDL_Thread *thread;
int threadReturnValue;
public:
inputHandlerClass();
int getInput(void *ptr);
void startThread();
};
//Default Constructor
inputHandlerClass::inputHandlerClass(){
this->thread = SDL_CreateThread(getInput, "inputThread", this);
}
int inputHandlerClass::getInput(void *ptr){
int cnt;
for(cnt= 0; cnt < 10; ++cnt){
std::cout << "counter: " << cnt << std::endl;
SDL_Delay(50);
}
return cnt;
}
void inputHandlerClass::startThread(){
SDL_WaitThread(this->thread, &this->threadReturnValue);
}
SDL_CreateThread expects a pointer to a regular function with int(void *ptr) signature as first parameter, however you are providing a non-static member function (not even a pointer because member functions aren't getting implicitly converted to a pointer). You should redeclare getInput as static. this pointer will be available as ptr.

std::stol corrupts stack on failure

class.h
// class.h
#pragma once
#include <string>
#include <iostream>
class TV {
public:
TV() {}
TV(std::string, std::string, std::string, std::string, std::string);
private:
int member;
};
main.cpp:
//main.cpp
#include "class.h"
TV::TV(std::string a, std::string b, std::string c, std::string d, std::string e) {
try {
member = std::stol(a);
if (member <= 0)
throw;
}
catch (...) {
std::cout << "Invalid argument" << std::endl;
}
}
int main(int argc, char *argv[]) {
new TV("TEST","NAME","0.1","0.1","0.1");
};
So it turns out that if I provided std::stol with an invalid_argument, then in gdb all other arguments passed to the function would appear corrupted.
Can anyone explain why this happens?