Segmentation fault while calling a method from a pointer [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to get a window size from a pointer on sf::RenderWindow, but when I call a method getSize() it gives me a segmentation fault:
sf::RenderWindow* winHandle;
void createHandle(sf::RenderWindow *rw, {...}){
winHandle = rw;
}
sf::Vector2i getWindowSize() const {
return static_cast<sf::Vector2i>(winHandle->getSize());
}
createHandle is acting like a constructor here, just sets the value of winHandle as a pointer to the RenderWindow.
Update:
after some research and debugging I determined that my problem was because of winHandle beeing null, but I still can't understand why does it work like that.
Well, I have two base classes UIHandle and UIElement, UIElement inherits UIHandle and any other UI element uses UIElement and releases It's functions.
like:
class UIHandle {
sf::RenderWindow* winHandle;
void createHandle({...});
{...}
};
class UIElement : public UIHandle {
void setHandle(UIHandle handle);
{...}
}
class anyOtherElement : public UIElement {
{...}
}
(The releasation might be questionable)
every element works the same way(which means it has the handle pointer), but for some reason not for UITitleBar
in main() firstly I create a Handle and then link this handle to every element:
sl::UIHandle testHandle;
testHandle.createHandle(&window, sf::Vector2i(0, 0), sf::Vector2f(800, 600));
testHandle.e = &e;
sl::TestButton buttonA("Test", 20, 20, 100, 20);
buttonA.setHandle(&testHandle);
sl::UIButton buttonB("Test", 60, 60, 100, 20);
buttonB.setHandle(&testHandle);
sl::UITitleBar TitleBar("Test titlebar");
TitleBar.setHandle(&testHandle);
Oh, well, even though the pointer is not null it still doesnt work as intented and causes a segfault with other UIElements.

My suggestion is to check whether the pointer is NULL or not before trying to access the content of the pointer. winHandle might be NULL or is not a valid pointer. It is very difficult to know the exact reason with the code you posted.
Segmentation fault happen in many cases as given below.
When pointer is NULL
When you try to alter the contents of readonly memory
When you try to use dangling pointer
You can read more on segmentation fault using this question on stack overflow
What is a segmentation fault?

Related

c++ attempting to reference a deleted function in non existing constructor (using rapidJson) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm currently getting this error:
'User::User(const User&)': attempting to reference a deleted function
The program passes a string value of an object into the class.
User Constructor:
User::User(string s){
int size = s.length() + 1;
char* cstr = new char[size];
strcpy_s(cstr, size, s.c_str());
user.Parse(cstr);
}
Main Loop:
int main(){
//json equals something similar to this: "{\"body:{[{"user":1},{"user":1},{"user":1}]}\"}";
const char * json;
Document d;
d.Parse(json);
if (d.HasMember("body")) {
if (d["body"].IsArray()) {
for (SizeType i = 0; i < d["body"].Size(); i++) {
string json = getJsonString(d["body"][i]);
User u = User(json); \\this is where the error point to
this->users.push_back(u);
}
}
}
}
getJsonString function:
string getJsonString(Value& value) {
StringBuffer buffer;
buffer.Clear();
Writer<StringBuffer> writer(buffer);
value.Accept(writer);
return string(buffer.GetString());
}
I search for a lot of explanation on this error but nothing seems to make sense to me. I think it has something to do with the vector array however it doesn't make sense to me as I'm not using a pointer or reference for any of the user value. It seems to point to the constructor however no pointer or reference is being passed through. I through by returning the string of the json, I wasn't using a pointer but maybe I actually am? I would be grateful for any explanation to what I am doing wrong.
User is not copyable; this means that:
User::User(const User&) (copy constructor) is private
or deleted (= delete;)
or deleted implicitly (e.g. class has non-copyable members, or inherits from a non-copyable class). Thank you Yksisarvinen for the comment
This means you are not allowed to create a new User from another one.
Then, if you want to store User objects in a vector (as you are "apparently" trying to do in your post, I say "apparently" because the posted code does not compile, I dunno who is this) you cannot store them by value, as the vector contained needs an accessible copy constructor.
See std::vector:
T must meet the requirements of CopyAssignable and CopyConstructible.
However, you can store them as pointers:
std::vector<std::shared_ptr<User>> users;
users.push_back( std::shared_ptr<User>( new User( json ) );

Why is "this" NULL? C++ Segmentation fault [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm building a Qt app and it's crashing because of a segmentation fault. After investigation, I found out that the cause of the segfault is that "this" is NULL and I try to access a member variable in the readInputFile(QString path) method.
In this line input += line;
I don't understand why this is happening. how can "this" be NULL ?
Here's where the object is created
void MainWindow::on_inpFileCheck_clicked()
{
if (ui->inpFileCheck->isChecked()) {
QString filePath = QFileDialog::getOpenFileName(this,tr("Open CSV file"), "/home", tr("CSV (*.csv)"));
myAlgo->readInputFile(filePath);
ui->inputEdit->clear();
ui->inputEdit->appendPlainText(myAlgo->getInput());
}
}
Here's the BaseAlgorithm header
#include "qstring.h"
#include "qmainwindow.h"
class BaseAlgorithm
{
public:
BaseAlgorithm();
QString readInputFile(QString);
int lenArr;
private:
QString input;
QString output;
};
And here's the implementation and where the problem happens
#include "basealgorithm.h"
#include "qfile.h"
#include "qtextstream.h"
BaseAlgorithm::BaseAlgorithm() {
numComparisons = 0;
input = "";
output = "";
intArr = NULL;
}
QString BaseAlgorithm::readInputFile(QString path) {
QFile inpFile(path);
if (inpFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&inpFile);
while (!in.atEnd()) {
QString line = in.readLine();
input += line; // crash happens here
}
return input;
}
else {
return "ERROR";
}
}
In C++, it is perfectly possible to call a method via a null pointer to an object. As long as this is not actually dereferenced, the function would work fine.
UPDATE: The behavior is what is often exhibited by implementations, as this is usually treated as just another parameter in the compiled code. However, as #manni66 points out, the standard doesn't actually mandate the result of calling a method on a nullptr.
It is pretty obvious that this is NULL because myAlgo is NULL where it is called. So the question asked in the title here is answered.
Why is myAlgo NULL? We don't know because you didn't show that code.
I fixed it. The object was being created late.

Pushing a DirectX object into a std::queue [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm working on a small release manager that will be used to delete objects once they are old.
I'm using a std::queue to hold the age & pointer to the object.
This is the method that I'm using to push values into the queue:
ID3D12Resource* texture; // declaration
renderPlat->PushToReleaseManager(texture);
std::queue<std::pair<int,void*>> mResourceBin; // declaration
void RenderPlatform::PushToReleaseManager(ID3D12Resource* res)
{
if (!res)
return;
mResourceBin.push(std::pair<int, void*>(0, res));
}
But this is causing an Exception thrown: read access violation / std::_Deque_alloc<std::_Deque_base_types<std::pair<int,void * __ptr64>,std::allocator<std::pair<int,void * __ptr64> > > >::_Myoff(...) returned 0x6B0 :
void push_back(value_type&& _Val)
{ // insert element at end
this->_Orphan_all();
_PUSH_BACK_BEGIN; // <--- The exception is thrown here!!!
this->_Getal().construct(
_Unfancy(this->_Map()[_Block] + _Newoff % _DEQUESIZ),
_STD forward<value_type>(_Val));
_PUSH_BACK_END;
}
The object that I'm trying to delete, is an ID3D12Resource it inherits from IUnknown
Edit:
I'm using: Visual Studio 2015 (v140).
Edit 2:
The ID3D12Resource* object passed to the PushToReleaseManager() is created using ID3D12Device::CreateCommittedResource
I found the problem.
I was getting the RenderPlatform which has the PushToReleaseManager() method like this:
auto rPlat = (dx11on12::RenderPlatform*)(renderPlatform);
This cast was failing because renderPlatform was invalid and it was returning a null pointer. The thing is that I was allowing me to call the method no problem, I guess because it had some junk memory around.
Thanks for the answers!
Try to use smart pointers. They are much better then explicitly try to release memory.

Classic List of object in C++ using pointers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'd like to make one directional list of objects in C++. I've got 3 classes: BasicMiachine,Desktop,Laptop. Two last classses extends BasicMachine. What I want to do is make a list of object (Desktop,Laptop) using only one list. In Basic Class which is abstract class (because I have declare one method as virtual) I have a field which is a pointer to next object is a BasicClass type. Below is my code:
int main () {
BasicClass* headList= NULL;
BasicClass* iterator = NULL;
while(....)
{
switch(.....){
case 1:
addNewComputer(headList,iterator,numberOfObjects);
break;
}
}
void static addNewComputer(BasicClass* headList, BasicClass* iterator,short numberOfObjects)
{
short choice;
cout<<"What is your machine?"<<endl<<"1) Desktop or2) Laptop"<<endl;
cout<<"Your choice: "; cin>>choice;
if(choice== 1)
{
//Add some data to variables// ....//
if(numberOfObjects == 0)
{
headList = new Desktop(wysokosc,dlugosc,szerokosc, taktowanieProcesora, numerIdentyfikacyjny, typProcesora, nazwaWSieci,ID);
iterator= headList ;
iterator->nextObject = NULL;
}
else
{
BasicClass* tmpIterator= NULL;
tmpIterator= headList ;
tmpIterator->nextObject = new Desktop(wysokosc,dlugosc,szerokosc, taktowanieProcesora, numerIdentyfikacyjny, typProcesora, nazwaWSieci,ID);
tmpIterator= pomocniczyWskaznik -> nextObject;
tmpIterator->nextObject = NULL;
}
}
else if(choice == 2)
{
//It is the same as above but I add here a La
}
};
After I add one and second computer I got an error like: "Access violation writing location 0x00000050." Is it a problem with pointers? I use BasicClass type pointers to hold both objects (Desktop, Laptop).
You make the classic mistake of passing pointers by value instead of by reference.
Change addNewComputer to e.g.
void static addNewComputer(BasicClass*& headList, BasicClass*& iterator,short numberOfObjects)
and things should work better.
I suggest you to take a look to standard containers. Anyway, the problem is that your are passing pointers by value, so when you call "new" the pointer inside addNewComputer() points to a new memory direction and when the function returns, headList and iterator are null (notice the memory leak issue). To solve your problem, you need to pass headList and iterator by reference i.e.
void static addNewComputer(BasicClass*& headList, BasicClass*& iterator,short numberOfObjects)
Hope this help.

Returning a pointer in C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 8 years ago.
Improve this question
I think my question sounds stupid and welcome downvote on me. If you are implementing a method in C++ which needs to return a pointer, is it safe to do that? If not, why?
Not a simple question. For instance: Best way of returning a pointer.
Ideally, you should try to avoid returning values that come with side-effects or obligations.
// This may be ok, it implies no burden on the user.
Manager* GetManager();
// But what if the user decides to call delete on the value you return?
// This is not unusual in C code, but carries a hidden contract:
// I allocate - you free.
const char* GetFilename(int fd)
{
char* filename = malloc(256);
sprintf(filename, "/tmp/tmpfile.%d", fd);
return filename;
}
C++ is about encapsulation and abstraction. You can codify the contract with your consumer by encapsulating a pointer you want to return. The idea here is that instead of exposing a pointer, you expose an object which is responsible for ownership of the pointer. Infact, recent versions of the language already do this for you with std::unique_ptr, std::shared_ptr and std::weak_ptr.
But a crude, simple RAII example might be:
class StrDupPtr
{
char* m_alloc;
public:
StrDupPtr(const char* src)
: m_alloc(strdup(src))
{}
~StrDupPtr()
{
free(m_alloc);
}
operator const char* () const { return m_alloc; }
// etc.
};
You're still returning a pointer here, but you've encapsulated it with a management contract and removed burden from the end-user to manage your resources.
You can't always avoid it, and when you have to, yes it can be dangerous.
int* AllocateMeSomeMemory()
{
int* memory = malloc(4 * sizeof(int));
// here, have four ints.
return memory;
}
int main() {
int* memory = AllocateMeSomeMemory();
memory[42] = 0xDeath; // yeah, it's not a valid hex number, but that's not really the problem.
}
Another common problem with pointers is that there's no way to tell how many people have them. Here's a contrived example:
void transferItem(userid_t user1, userid_t user2, itemid_t item) {
Account* a1 = GetAccount(user1);
Account* a2 = GetAccount(user2);
if (a1 != a2) {
transferItemInternal(a1, a2, item);
}
delete a2;
delete a1; // Sorry Dave, I can't do that. How about a nice game of CRASH?
}
Normally, a2 and a1 will be different, but when they're not...
Another common failure pattern with pointers is asynchronous callbacks:
// ask the database for user details, call OnLoginResult with userObj when we're done.
void login(int socket, userid_t userId, passwordhash_t pass) {
User* userObj = GetUserObj(userId, socket);
Query* query = Database()->NewQuery("SELECT * FROM user WHERE id = ? AND password = ?", userId, pass);
Database()->Queue(query, OnLoginResult, userObj);
}
void OnDisconnect(int socket, int reason) {
User* userObj = GetUserBySocket(socket);
if (userObj) {
UnregisterUserObj(userObj);
delete userObj;
}
}
void OnLoginResult(void* param) {
User* userObj = static_cast<UserObj*>(param);
// all well and good unless the user disconnected while waiting.
...
}
Yes it is. I assume you mean "Allocate and return" a pointer.
Its common to have initialisation functions which allocate a pointer to an object of some type, and then initialise the object itself. It will then be up to a different part of the program to release the memory.
Well it always depends on what you are doing. A pointer is simply a memory address, so it is similar to simply returning an integer. You should do more research on pointers and how to properly implement them
I sense this question might be closed quite soon, but I'll try to answer anyway.
Yes, it's "safe", as long as you're careful. In fact, it's a very common way to do things, particularly if you're interfacing with C APIs. Having said that, it's best to avoid doing so if you can, because C++ generally provides better alternatives.
Why should you avoid it? Firstly, let's say you have a method that looks like this:
MyStruct* get_data();
Is the return value a pointer to a single instance of MyStruct, or the start of an array? Do you need to free() the returned pointer? Or perhaps you need to use delete? Can the return value be NULL, and what happens if it is? Without looking at the documentation, you have no way of knowing any of these things. And the compiler has no way of knowing either, so it can't help you out in any way.
Better options:
If you want to return an array of values, use a std::array (if the size is fixed at compile-time), or a std::vector (if the size isn't known till run-time).
If you're trying to avoid copying a large struct, then return a reference, or a const reference if possible. That way the caller knows they won't receive a NULL value.
If you really need to return a pointer, than consider using a smart pointer instead -- that will help you sort out ownership issues. For example, std::shared_ptr uses reference counting, and std::unique_ptr ensures that a given pointer only ever has one owner.