core dump segmentation fault with C++ - c++

I am a newbie to the C/CPP application and analysing an issue with a piece of C/CPP code. I came across a Segmentation Fault error and I am not to identify the root cause of the segmentation fault.
Please find the scenario below:
union Value
{
int value_int;
float value_float;
RWCString *value_string;
}
void setValueString(const RWCString &value_string_arg)
{
*(value.value_string) = value_string_arg; //value is a reference to UNION Value.
}
when an application makes use of this piece of code, then it generates a segmentation fault at runtime and terminates. I placed few console output statements and understood that the segmentation fault may be due to
*(value.value_string) = value_string_arg;
line.
Could anyone please validate my identification of the segmentation fault? Also, I am not pretty sure as to get around this issue. Please let me know if a anyone has got thoughts on the same.
Any help is much appreciated. Thanks
~Jegan

You probably want to do something like:
value.value_string = new RWCString(value_string_arg);
In your code, if value.value_string is an uninitialised pointer, then the assignment you're doing will try to write to some random part of memory, causing the segmentation value. In my code above, the new operator allocates a new block of memory for a RWCString and calls the copy constructor to copy the value_string_arg. Then it assigns the pointer to the newly allocated block of memory to value.value_string.
Don't forget to delete value.value_string later when you're done with it to avoid a memory leak!

When you do *(value.value_string), you are dereferencing the pointer, i.e. you are asking the compiler to set the value of the thing pointed to by value.value_string. You need to make sure that it points at a valid piece of memory. If you don't, then when you assign to it, you will end up writing to a random location in memory, hence the segmentation fault.
In C++, you would typically get a valid piece of memory by doing something like value.value_string = new RWCString; beforehand (and making sure you delete it when you are done). However, this is dangerous in your situation, because you have created a union of the pointer. As soon as you write to e.g. value.value_float, you will have lost the pointer value, and you'll have a memory leak.

Try analyzing the core dump with gdb. The core dump should show you exactly where the seg fault is occurring. You will need to compile with debugging enabled.

(The language you are using is C++. Not C/CPP or C/C++.)
The main problem here: You are using a union. Beginners should probably not use unions, because if you initialize one member and then try to use another, you blow up.
So pretending there's no union and you really do have a RWCString* pointer: Are you sure it points at a valid object? When was the RWCString constructed, and what is its lifetime?
Of course, segmentation faults don't always happen right at the invalid code. You might have something else bad happening before that, then biting you later.

Related

Segmentation violation when trying to access vector entry

I've created a class, say I named it MyClass, as well as another that inherits from it, say MyClassDaughter then I tried the following:
MyClassDaughter *MyClassDaughterPointer;
vector <MyClass*> MyClassVector;
MyClassVector.push_back(MyClassDaughterPointer);
MyClassVector[0]->SetSomethingInMyClassDaughter;
When I try to run the executable it says "Segmentation Violation".
(I think must say that my code has some Root stuff in it... Could that be the problem? Anyways, I know that, usually, segmentation violation errors are cause by trying to access memory that we don't have permission to access, but I think I do have permission to access this memory. Am I wrong?)
You do not initialize MyClassDaughterPointer, so you push some random (wild) pointer to the vector.
You need to create new instance of MyClassDaughterPointer. Assuming you have a default constructor, it will look like this:
MyClassDaughter *MyClassDaughterPointer = new MyClassDaughterPointer();
The pointer
MyClassDaughter *MyClassDaughterPointer;
Was never set to anything but there is some uninitialized content if that was on the stack or just null is that was static. Therefore you cannot try to access it as you do, that causes Undefined Behavior.
MyClassVector[0]->SetSomethingInMyClassDaughter; // that is same pointer set in vector entry
Unsure what compiler does as long as it usually has such code to be optimized out and that should not have any effect - no job for CPU here at all as long as that pointer is not used. But debug mode is right always attempting to load the address to some register.

Checking if an C++ Pointer is valid (in Objective-C(++))

I've adapted Matt Gallagher's "Testing if an arbitrary pointer is a valid object pointer" in an iOS project which uses Objective-C++. It's working fine with Objective-C objects but it always tells me that my C++-Pointers are invalid regardless of whether it works or not. Sometimes the Code crashes at the pointer. Sometimes the code works fine. But the test-method always tells me the pointer is wrong.
Is here anybody who knows to adapt this code to C++ classes and objects too? I could imagine that the code is only working with Objective-C according to the use of "Class"
The contents of a pointer variable is either: A null pointer, a valid pointer to an object, a valid pointer to an array element or past the last element of an array, or some invalid pointer.
If it is an invalid pointer, then any attempt to use it invokes undefined behaviour. That includes any attempt to check that it is an invalid pointer. And there you are stuck. All you can do is check whether it is a null pointer, or whether it is equal to some other valid pointer.
You should go with the Objective-C philosophy: Trying to use an invalid pointer is a programming error. You don't try to detect and handle this at runtime. You let it crash and fix the bug in your code.
C++ pointers simply reference an address in memory. You could look at what's there in memory using a memory viewer tool, but that wouldn't even guarantee that the memory is still valid. For example:
char* test = new[13];
strcpy(test, "Hello World!");
delete[] test;
.
.
.
printf("%s", test);
In some cases this will print successfully. Sometimes it will print a garbage string. And sometimes it will segfault. There is nothing there to speak to the pointer's validity.
If you're looking at a program that has just segfaulted and you're trying to see what happened there are a few options available to you:
You can look at the memory through a memory viewer, that in combination with the line you faulted on can provide insight.
You can seed your memory before running to make this clearer use 0xbadfood5 or something similar.
Use Valgrind when running is a great tool, if you can deal with the overhead.
The best option is to do error checking in your code. It sounds like you don't have that or you wouldn't be here. Preconditions and postconditions are great and will save you a ton of time in the long run (like now.) However as a silver lining you should exploit this to exact better coding standards in your organization for the future.

C++ function used to work, now returning 0xfdfdfdfd

I have some code I wrote a few years ago. It has been working fine, but after a recent rebuild with some new, unrelated code elsewhere, it is no longer working. This is the code:
//myobject.h
...
inline CMapStringToOb* GetMap(void) {return (m_lpcMap);};
...
The above is accessed from the main app like so:
//otherclass.cpp
...
CMapStringToOb* lpcMap = static_cast<CMyObject*>(m_lpcBaseClass)->GetMap();
...
Like I said, this WAS working for a long time, but it's just decided to start failing as of our most recent build. I have debugged into this, and I am able to see that, in the code where the pointer is set, it is correctly setting the memory address to an actual value. I have even been able to step into the set function, write down the memory address, then move to this function, let it get 0xfdfdfdfd, and then manually get the memory address in the debugger. This causes the code to work. Now, from what I've read, 0xfdfdfdfd means guarding bytes or "no man's land", but I don't really understand what the implications of that are. Supposedly it also means an off by one error, but I don't understand how that could happen, if the code was working before.
I'm assuming from the Hungarian notation that you're using Visual Studio. Since you do know the address that holds the map pointer, start your program in the debugger and set a data breakpoint when that map pointer changes (the memory holding the map pointer, not the map pointed to). Then you'll find out exactly when it's getting overwritten.
0xfdfdfdfd typically implies that you have accessed memory that you weren't supposed to.
There is a good chance the memory was allocated and subsequently freed. So you're using freed memory.
static_cast can modify a pointer and you have an explicit cast to CMyObject and an implicit cast to CMapStringToOb. Check the validity of the pointer directly returned from GetMap().
Scenarios where "magic" happens almost always come back to memory corruption. I suspect that somewhere else in your code you've modified memory incorrectly, and it's resulting in this peculiar behavior. Try testing some different ways of entering this part of the code. Is the behavior consistent?
This could also be caused by an incorrectly built binary. Try cleaning and rebuilding your project.

What could be causing this memory access error (C++)? Might be undefined behavior?

I have a relatively large class that I'm working with and it's all worked fine so far (note: I didn't actually write the class, I'm just adding some functionality). However, after declaring one more string in the header file, everything now crashes (I get a memory access error). If I erase that string and rebuild, everything works fine.
I'm not actually doing ANYTHING with that string....just the act of declaring it is causing some weird memory error.
I can't explain in much more detail than this, since it would be a waste to try to explain every function. What kind of things should I look for here to find the problem? What might cause this weird behavior?
The error itself is:
Unhandled exception at 0x65fd17fd (msvcp80d.dll) in myFile.exe: 0xC0000005: Access violation writing location 0xcdcdcdcd.
Basically all that changed in the .h file was:
StringType string1;
Turned into:
StringType string1;
StringType string2;
StringType is an extension of basic_string
You've allocated some memory on the heap and failed to initialize it.
0xcd is a fill pattern used by the debug heap: before dynamically allocated memory is given to your program, it is filled with that pattern to help you find uninitialized variables.
As for why changing the class definition affects the outcome, you may be doing incorrect pointer arithmetic, accessing something beyond the end of a dynamically allocated object, or one of any number of other things that no longer manifests as a bug when you have a larger object. You could also be violating the one-definition rule if some of the source was built using the old definition and some of the source is built with the new definition.
There are many things that can cause this kind of problem: your best bet is to break in the debugger when it happens, and trace backwards to see where the error originated (sometimes this can be lots of fun; I had to trace an uninitialized variable across a network connection once).

problem with containers: *** glibc detected *** free(): invalid pointer: 0x41e0ce94 ***

I have a C++ program on Linux that crashes after some time with the message:
*** glibc detected *** free(): invalid pointer: 0x41e0ce94 ***
Inside the program I make extensive use of containers. They have to store objects of a simple class.
EDIT 2009-4-17:
In the meantime it seems clear that the error has nothing to do with the simple class. The error still occurs if I change the containers to hold other datatypes. The problem must be somewhere else in my code, I'm trying to figure it out at the moment...
Consider using a std::string to hold the string value instead of a raw char pointer. Then you won't have to worry about managing the string data in your assignment, copy, and destruction methods. Most likely your problem lies there.
Edit: There's no issue with the newer class you posted, and no problem with the first version if you're only using the char * to point to string constants. The problem lies elsewhere in the program or with the way you're using the class. You'll have to spend more time digging in the debugger and/or valgrind to track down the problem. I would figure out what is pointed to at the specified address and try determine why it's being freed twice.
At a guess, there is something wrong in your copy ctor, assignment op or destructor - you need to show the code for those.
Edit: Just noticed you don't have an assignment operator - assuming your copy constructor & destructor are OK, you need an assignment operator too, as the std:; containers will use it.
I have been fighting with a C/C++ application we are developing, and the first ideas that come to my mind are
A pointer has been modified and its pointing to an invalid possition (ptr++;) or something like that.
You have freed the object, but the pointer still holds the direction.
A tool like Valgrind may help you to detect possible errors in the code. To install:
sudo apt-get install valgrind
And to use it:
valgrind --tool=memcheck --leak-check=full ...
It will report errors while the program is running, and it will give you also a report after the program ends. The only problem is what valgrind identifies as a possible problem may not be a real problem. But it is an starting point.
It's most certainly a bad string value. Using std::string maybe help in this regard if it is a dangling pointer issue. Also ensure all the string initializations work as expected.
If I understand the class correctly, you assume that whatever memory resides at m_cstring won't be deallocated for the lifetime of the class. Which in your case also means for the lifetime of the containers. Check your scopes.
Another problem you may be encountering is if your Destructor is deleting the cstring then using a default value in the constructor is a really bad idea as you will be trying to deallocate a statically allocated cstring.
It is possible in C++ to define a function that is supposed to return a string, but doesn't return anything and you wind up with a bad string (Typically the compiler will catch the 'Reached end of non-void function', but not always).
Ditto on using valgrind.
As an addendum after reading various comments, there's always the possibility that a memory error somewhere else in the program corrupted one of the strings.
EDIT 4-16
At this point I would verify the values of the object are well formed on construct/destruct. (try printing them?) If everything looks good, you may have to look elsewhere in your code for the error.
What is inside your destructor? Probably it does free of the cstring. And If it is the case then you share your cstring pointer over instances and each instance then frees the same pointer.