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.
Related
I've got a large Mac app that runs for a couple of days at a time operating on a large data set. It's a mix of Objective-C++ and C++. It runs great on Mountain Lion, but on Mavericks, after running for about 10 to 20 minutes (in which a couple of million objects are allocated and destroyed), it crashes. It behaves as if it's crashing with an invalid pointer (i.e. calling a function on a deleted C++ object), but the object it's pointing to is in a state that makes absolutely no sense.
All my C++ classes inherit from a common base class where the constructor looks something like this:
MyClass::MyClass()
{
mCreated = 12345; //int member variable set here and NEVER TOUCHED AGAIN.
//other initialization stuff
}
When it crashes, the debugger shows that in the bad object, the value for mCreated is 0. It's behaving as if the object never ran its constructor!
I don't think it's memory stomping, because this value is never anything other than 0 or its expected value, and none of the other fields in the object have values that look like the garbage you'd expect from memory stomping.
I've also tried running with scribble turned on, and the 0x555 and 0xaaa values don't show up anywhere. I've also tried Guard Edges.
In-depth investigation has not revealed anything. The bad object isn't even always the same class. All I can think of is that something with the new memory stuff in Mavericks (compressing unused memory) is causing some new behavior (maybe a bug or maybe some previously unknown, mostly-unenforced rule that now really matters).
Has anyone seen anything similar? Or does anyone know of any mostly-unknown memory rules that would apply more strongly under Mavericks?
I think you're right about the invalid pointer suspicion. It might be a pointer to a deleted object or it might be a garbage pointer. Either one would be consistent with the mCreated member being different than you expect. In the case of a deleted object, the memory could be used for something else and therefore set to some other value. In the case of a garbage pointer, you're not pointing to anything that ever was an instance of your class.
I don't know how well the Allocations instrument works for C++ objects, but you could try reproducing the crash under that. When it stops in the debugger, get the this pointer and then get the history of that address from Instruments.
If Instruments doesn't work, you can set the MallocStackLoggingNoCompact environment variable. Then, when it stops in the debugger, examine the this pointer and use the following commands to view the history of that address:
(lldb) script import lldb.macosx.heap
(lldb) malloc_info --stack-history 0x10010d680
(Use the this address instead of 0x10010d680, of course.)
Alternatively, you can use the malloc_history command from a shell to investigate the history, if doing it within LLDB is cumbersome.
I got a program which uses a lot for memory for computations. Not too much, I guess. All bif arrays are stored at heap, of cause. MS VS 10 is my IDE. Task manager in Windows says it takes 1548 Kb. I am still writing it, and at some point I added
bool* mask= new bool [numberOfUnknowns];
and numberOfUnknowns is about 1600. It is in the public method of one of the classes (not sure if it matters). And I get
Unhandled exception at 0x777615de in ProgrammName.exe: 0xC0000005:
Access violation writing location 0x006a2000.
at this line. And it works with hard-coded
new bool [10];
and fails with
new bool [1600];
So, am I reaching possible memory size? Or should I check something else? I don't believe that I can't get more memory because putting
double* a = new double [100000];
in the main just for check makes memory size greater but the run-time error is on the same position.
Thanks in advance.
Addition 1:
I put the call of method that contains this line before all other calls and it worked. So, I guess, it's memory issue because of some memory allocated/freed during the work of other methods of my class. So, how is it possible? Should I post some more code or there is a common solution/description for such cases?
Addition 2: And for std::vector - need to find out what's wrong now, don't want to leave this problem without understanding.
Thanks for style correction of the post!
Use a std::vector. Your error is basically accessing memory you no longer own- either because you already freed it or past the end or something like that. You need to use a class-based solution to prevent this problem.
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.
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).
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.