Segfault trying to strcpy a char * - gdb

I am in a introductory C++ course and my program is segfaulting in my copy function. when I use GDB it says it cant access the char * at location 0x0. the odd thing is that I have written this function many times before without any errors.
class question
{
public:
question();
~question();
int set_question(char * question);
int copy_question(question & to_copy);
int clear_question();
int display();
char* retrieve_question();
char* retrieve_answer();
private:
char* your_question;
char* correct_answer;
};
///////////////////
int question::set_question(char * question)
{
your_question = new char [strlen(question)+1];
strcpy(your_question, question);
}
this is the error code in GDB
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 1 (LWP 1)]
0x00013af8 in question::set_question (this=0x0, question=0x257a8 "do you like movies??")
at question.cpp:51
51 your_question = new char [strlen(question)+1];
(gdb) p strlen(question)
$1 = 27
(gdb) p your_question
Cannot access memory at address 0x0

I'm not professional at C++, but before you call member function set_question, are you initialized the class question? It seems that the question class is not initialized.

You are calling the set_question method on a non-initialized object. You can see this from GDB output:
question::set_question (this=0x0, question=0x257a8 "do you like movies??")
'this' should not be 0x0
The problem is outside of this method. Basically, the newly allocated array cannot be assigned to 'your_question' member because the whole 'question' object is non existent.
You are probably not doing exactly the following, but this should illustrate the problem:
question *q = NULL;
q->set_question(...);

Related

Process returned -1073741819 (0xC0000005) problem on insertion of value

I am trying to create an AVL Tree and insert a node into it. Whenever I try to add a data value ın the tree node, my program crashes and returns the value 0xC0000005. This is how I have introduced the data item in the header file:
class AVLTreeNode
{
public:
int data;
AVLTreeNode();
virtual ~AVLTreeNode();
AVLTreeNode(int d, AVLTreeNode *leftChild, AVLTreeNode *rightChild);
AVLTreeNode *leftc;
AVLTreeNode *rightc;
int height;
}
Whenever I try to run the following lines of the code in the insert function, I get the crash.
AVLTreeNode *nw = NULL ;
nw->data = v;
I don't know what I'm doing wrong, please help me.
The return code of 0xC0000005 means STATUS_ACCESS_VIOLATION. (You can find this and other NT status codes on MSDN: NTSTATUS Values.) The error happens because NULL is outside the range of valid addresses for your program. Before dereferencing a pointer variable, you must assign it the address of a valid object. For example:
AVLTreeNode* nw = new AVLTreeNode{};
nw->data = v;
AVLTreeNode *nw = NULL;
This line of code sets nw to be a null pointer, in other words, it doesn’t point at anything. Trying to dereference a null pointer will result in undefined behaviour. You need to allocate memory for an AVLTreeNode object, and then get nw to point at it.
What you need instead is this, which allocates memory and points nw at it:
AVLTreeNode *nw = new AVLTreeNode;
And remember, whenever you allocate memory with new you need to deallocate it when you're finished with it:
delete nw;

Pass / copy pointer to another pointer

I have a pointer code as follows :
class NsObject : public TclObject, public Handler {
public:
NsObject();
virtual ~NsObject();
virtual void recv(Packet*, Handler* callback = 0) = 0;
virtual void recv(Packet* p, const char* s);
}
NsObject* uptargetTX;
NsObject* uptarget_;
void NsObject::recv(Packet *p, const char*)
{
Packet::free(p);
}
if (NodeType_ == TX) {
uptarget_->recv(ppp, (Handler*) 0);
*uptargetTX = *uptarget_; //in this line error happens
}
I want to pass/copy the pointer uptarget_ to uptargetTX by using *uptargetTX = *uptarget_; but something goes wrong
segmentation fault (core dumped)
Then I change to uptargetTX = uptarget_; but same error occurs. How to remove this error ?
uptargetTX and uptarget_ are unininitialized, so they point to random memory locations, so access causes a segmentation fault. Depending on what you are trying to do, you probably have to allocate memory first for example like this: NsObject* uptargetTX = new NsObject
I have no idea of what your code does but this
NsObject* uptarget_;
uptarget_->recv(ppp, (Handler*) 0); <- dereference the pointer
is wrong in the first place: you need to initialize that pointer to something valid before.
The rest is also wrong for the same reason.

maps initialization in c++ for implementing tries

I am trying to implement tries in c++. Here is the structure I have used:
typedef struct tries{
int wordCount;
int prefixCount;
map<int,struct tries*> children;
}tries;
The initialize method:
void initialise(tries *vertex)
{
vertex = (tries*)malloc(sizeof(tries*));
vertex->wordCount = vertex->prefixCount = 0;
for(char ch='a';ch<='z';ch++)
vertex->children[ch]=NULL;
}
The initialize method has segmentation fault at vertex->children[ch]=NULL; The fault is:
Program received signal SIGSEGV, Segmentation fault.
0x000000000040139a in std::less<int>::operator() (this=0x604018,
__x=#0x21001: <error reading variable>, __y=#0x7fffffffddb8: 97)
at /usr/include/c++/4.6/bits/stl_function.h:236
236 { return __x < __y; }
What is wrong?
You should not use malloc() if you are working with C++. Also, you should not allocate enough memory to hold a pointer (sizeof(tries*)) if you need to create an object the size of a tries.
Use the new operator:
vertex = new tries();
Or even better, do not use new at all and avoid doing manual memory management with raw pointers, new, and delete. Consider using smart pointers instead.
Also, in C++ classes have constructors, so the initialise() method could actually be replaced by a constructor for tries:
struct tries
{
tries() : wordCount(0), prefixCount(0)
{
// ...
}
int wordCount;
int prefixCount;
map<int, struct tries*> children;
};

Receiving segmentation fault in C++ code

I'm using C++, code::blocks (with warnings enabled and I checked to make sure) and SFML.
I've tried hunting the bug down myself but I really can't find what's wrong. I know what a segfault means but this one really has me stumped. I'm a beginner may I add but am quickly learning.
I've got a basic main class void Engine that has a method void RenderFrame that renders every frame of the application. Inside said method I have this code which is supposed to draw all the tiles onto the renderwindow:
Tile* tile;
for (short y = 0; y < mapHeight; ++y) {
for (short x = 0; x < mapWidth; ++x) {
tile = currentLevel -> GetTile(x, y);
if (tile) {
tile -> Draw((x * tileSize), (y * tileSize), Wnd);
}
}
}
The GetTile method is supposed to return a tile from within a std::vector<std::vector<Tile *> >
The Draw method only does this:
void Tile::Draw(int x, int y, sf::RenderWindow *pWnd) {
sprite.SetPosition(x, y);
pWnd -> Draw(sprite);
}
The application compiles just fine, but it crashes right after calling sprite.SetPosition(x, y);
This is the full call stack from the debugger:
#0 68701829 sf::Drawable::SetPosition(float, float) () (D:\Coding\C++\sfml\bin\debug\sfml-graphics.dll:??)
#1 004021F9 Tile::Draw(this=0x76ab8cd5, x=0, y=0, pWnd=0x3e3310) (D:\Coding\C++\sfml\include\Tile.cpp:12)
#2 00401D7E Engine::RenderFrame(this=0x3e3298) (D:\Coding\C++\sfml\include\Engine.cpp:106)
#3 00401B29 Engine::MainLoop(this=0x3e3298) (D:\Coding\C++\sfml\include\Engine.cpp:63)
#4 00401E27 _fu0___ZTIPKc(this=0x3e3298) (D:\Coding\C++\sfml\include\Engine.cpp:119)
#5 004022D6 main() (D:\Coding\C++\sfml\Main.cpp:8)
I hope this is enough information to go on, and thanks in advance.
Edit: Oh, and this is from the debugger output. Program received signal SIGSEGV, Segmentation fault.
In sf::Drawable::SetPosition(float, float) ()
Doesn't give much more information about the problem.
This line in the backtrace looks suspicious:
#1 004021F9 Tile::Draw(this=0x76ab8cd5, x=0, y=0, pWnd=0x3e3310)
This seems to correspond to your Tile::Draw function, except the this pointer is misaligned, which suggests that it's not a valid pointer. So perhaps your std::vector<std::vector<Tile *> > has been corrupted somehow.
The most probable explanation is that the pointer returned by currentLevel->GetTile(x,y) is not valid. This could be because it was not properly initialized (to either NUL or a valid allocated object) or because the object to which it refers has been destroyed. Both would explain that sprite is not a valid object and calling SetPosition on that object will pass an invalid this pointer that would trigger the SIGSEGV.
A general cause of segmentation faults is dereferencing a null or invalid pointer.
1. Check GetTile(), is this causing the fault?
2. Check currentLevel before dereferencing.

pointer segfault problems

pointer segfault problems...
I've been doing c++ for some weeks meanwhile but i ran again into that issue.
basically i have these classes given. I cant change them. I start with an instance of _ns3__importAuftragResponse kout;
class SOAP_CMAC _ns3__importAuftragResponse
{
public:
ns2__SOAPImportResult *return_;
...
class SOAP_CMAC ns2__SOAPImportResult
{
public:
bool *error;
int *numberOfIgnoreds;
....
My code needs to check for the numberOfIgnoreds
first approach
ns2__SOAPImportResult* imp_result;
imp_result = kout.return_;
int num;
num = *imp_result->numberOfIgnoreds;
or i use
ns2__SOAPImportResult imp_result;
imp_result = *(kout.return_);
int* num;
*num = *imp_result.numberOfIgnoreds;
I mostly get segmentation fault
I know generally what happens at runtime but cant come up with the correct ode. PLease help.
EDIT
made progress thx to your answer, Nawaz , but still need some understanding
ns2__SOAPImportResult * imp_ptr = new ns2__SOAPImportResult;
imp_ptr = kout.return_;
int * num = new (int);
// next line segfaults
*num = *imp_ptr->numberOfIgnoreds;
what's hard for me to understand is, how or why allocate memory for something that is already "there" as there is the member return_ of the object kout
So is it correct to say I need to allocate memory for the variable I assign it to (which is of same type of course)?
Most likely you've not allocated memory for the following members which you're using in the code you've quoted.
ns2__SOAPImportResult *return_; //in the class _ns3__importAuftragResponse
int *numberOfIgnoreds; //in the class ns2__SOAPImportResult
Other than this I don't see anything where things might go wrong!
Make sure you allocate memory for these members (and all other pointers in your program) before using them. You can use new to allocate memory. Or alternatively, you can use malloc() as well. Whatever you use, use it consistently, and deallocate the memory once you done, using delete or free() respectively!
This looks like gsoap. In that case you must use soap_malloc to allocate memory which you return.
For example on the FAQ page, you will find this example:
int ns__itoa(struct soap *soap, int i, char **a)
{ *a = (char*)soap_malloc(soap, 11);
sprintf(*a, "%d", i);
return SOAP_OK;
}