AccessViolationException when string is too long (C++) - c++

I asked a similar question a couple of days ago, but I'm looking for more insight. I'm getting an AccessViolationException when I add a string to my program:
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at _cexit()
at <CrtImplementationDetails>.LanguageSupport._UninitializeDefaultDomain(Void * cookie)
at <CrtImplementationDetails>.LanguageSupport.UninitializeDefaultDomain()
at <CrtImplementationDetails>.LanguageSupport.DomainUnload(Object source, EventArgs arguments)
at <CrtImplementationDetails>.ModuleUninitializer.SingletonDomainUnload(Object source, EventArgs arguments)
The program has a bunch of const std::string's at the top level:
const std::string caseDelimitedOption = "CaseDelimited";
const std::string endOfLineOption = "EndOfLine";
const std::string functionNameDelimitWordsOption = "FunctionNameDelimitWords";
const std::string functionNameStartCaseOption = "FunctionNameStartCase";
const std::string indentStringOption = "IndentString";
const std::string lowerCaseOption = "LowerCase";
const std::string newLineBetweenDoAndWhileOption = "NewLineBetweenDoAndWhile";
const std::string nextLineOption = "NextLine";
const std::string nextLineAsWellAsCloseParenOption = "NextLineAsWellAsCloseParen";
const std::string noBracesAroundSingleStatementBlockOption = "NoBracesAroundSingleStatementBlock";
const std::string openBraceLocationOption = "OpenBraceLocation";
const std::string underscoreDelimitedOption = "UnderscoreDelimited";
const std::string upperCaseOption = "UpperCase";
const std::string whiteSpaceBeforeLeadingCmntOption = "WhiteSpaceBeforeLeadingComment";
If I replace last string with:
const std::string whiteSpaceBeforeLeadingCmntOption = ""; //"WhiteSpaceBeforeLeadingComment";
then the exception goes away. Is this just extra memory (from the string) hitting some bad memory that was caused elsewhere in my program? Or is the exception related to the string?
Thanks for any help,
Joe

I assume these strings are global variables.
Are you trying to access these strings from the constructor of another global variable (or from some method that is called before main is entered)?
If this is the case you are suffering from the probelem that global variable initialization order is undefined across multiple compilation units. There are a few solutions but more information about your application would probably be useful.
First test to see if main is even entered.
I would think that it working with the empty string is the result of some compiler optimization trick.

Try
valgrind --leak-check=full your.exe
and remember to compile your application with -g to get source code line in the executable.

The problem isn't the string. Somewhere in your program, you're reading or writing out of bounds. This results in undefined behavior, meaning that the program might appear to run, you might get an access violation, or it might crash with another error, or... anything else might happen.
The reason the string appears to make a difference is simply that it changes the program subtly, causing the out-of-bounds access to reach an unallocated page.

Related

How can I ensure that correct function is called in case there are multiple candidates

In C++ is perfectly legitimate to do:
bool x = "hi";
Because "hi" is translated by compiler to a char array and returns a pointer to that array, which is a number and number can be implicitly converted to bool (0 is false, anything else is true).
So I have these ctor:
Exception(QString Text, bool __IsRecoverable = true);
Exception(QString Text, QString _Source, bool __IsRecoverable = true);
Sadly I figured out that calling
Exception *e = new Exception("error happened", "main.cpp #test");
It creates a new instance of "Exception" class which is created using Exception(QString Text, bool __IsRecoverable = true); constructor, which is wrong to a point.
Is there a simple way to ensure that correct function is called, other than restructuring the constructors entirely, changing position of arguments, etc?
Firstly, I'm not sure why you're dynamically allocating an exception class. I'm not sure that's ever a good idea.
You can explicitly construct a QString:
Exception e("error happened", QString("main.cpp #test"));
Or you can pass the third argument:
Exception e("error happened", "main.cpp #test", true);
Or you can add an additional constructor that takes const char* and will be preferred over the conversion to bool:
Exception(QString Text, const char* Source, bool IsRecoverable = true);
You can easily make this forward to the QString version. Also note that names beginning with an underscore and a capital letter or with two underscores are reserved.
My suggestion would be to not use default arguments. They contribute to overload resolution problems like this, and anyway it is not very readable to just see true as an argument. Whoever's reading the code then has to stop and go look up what the true means. Even if it's yourself you may forget it in a few months time when you come back to the code, especially if you do this sort of thing a lot.
For example:
struct Exception: public whatever
{
Exception(char const *text);
Exception(char const *text, char const *source);
};
struct RecoverableException: public Exception
{
RecoverableException(char const *text);
RecoverableException(char const *text, char const *source);
};
It's a little bit more typing in this source file but the payoff is that your code which actually uses the exceptions is simpler and clearer.
To implement these constructors you could have them all call a particular function in the .cpp file with relevant arguments selecting which behaviour you want.
I have a preference for using char const * rather than QString as I am paranoid about two things:
unwanted conversions
memory allocation failure
If constructing a QString throws then things go downhill fast. But you may choose to not worry about this possibility because if the system ran out of memory and your exception handling doesn't prepare for that possibility then it's going to terminate either way.

Segmentation Error when using basic_string.h +operator

I have a simple code which is basically like the one below:
static std::string const part1[] = {"Test1", "Test2", "Test3"};
static std::string const part2[] = {"Pass", "Fail", "Retry"};
std::string test = part1[1] + part2[0];
I have included the string which in turn has the basic_string.h. I know that there is an overloaded +operator there.
When I built this I got no errors but when I tried to run it, I got a segmentation error.
The problem I noticed later is that if I simply try to print the array elements, I am seeing the same segmentation error.
I don't see where the memory leak is happening. Any clues?
In c++ array declaration is not possible in the way you used in your code.
A Valid code example is
static std::string const part1[] ={"Test1", "Test2", "Test3"};
static std::string const part2[] = {"Pass", "Fail", "Retry"};
std::string test = part1[1] + part2[0];

Cocos2d-x: Crash when initiating TMXTiledMap from string

I'm having problems creating a tmx map from string input.
bool LevelManager::initLevel(int currentLevel)
{
const char* map;
try {
map = LevelManager::getLevel(currentLevel);
} catch (int) {
throw 1;
}
if(map != NULL){
CCLog("%s", map);
tileMap = CCTMXTiledMap::create(map);
tileMap->setAnchorPoint(ccp(0,0));
tileMap->setPosition(ccp(15,20));
this->addChild(tileMap, 5);
backgoundLayer = tileMap->layerNamed("Background");
} else {
throw 1;
}
return true;
}
Thats my code.
It is very unstable. Most of the times it crashes and sometimes it doesn't.
I'm loading my map from the string map. Wich is a const *char.
My map is named Level1.tmx and when i load the map like this: tileMap = CCTMXTiledMap::create("Level1.tmx"); it always works and never crashes.
And i know for a fact that the value of map is Level1.tmx because i log it in the line before the load.
When it crashes the log outputs this: (lldb)
and on the line tileMap->setAnchorPoint(ccp(0,0)); it says "Thread 1: EXC_BAD_ACCESS (code=2, adress=0x0)
Does anyone know why this happens and how to fix it?
Many thanks.
Ps: i'm using xcode, the latest cocos2d-x release and the iPhone simulator
Edit:
Using breakpoints i checked where things go bad while loading the tilemap.
on the line tileMap = CCTMXTiledMap::create(map);
my variable map is still fine
but on line tileMap->setAnchorPoint(ccp(0,0));
it is suddenly corrupted (most of the time)
It sounds like you're returning a char* string created on the stack, which means the memory may or may not be corrupted, depending on circumstances, moon phases, and what not.
So the question is: How is getLevel defined and what does it do (post the code)?
If you do something like this:
const char* LevelManager::getLevel(int level)
{
char* levelName = "default.tmx";
return levelName;
}
…then that's going to be the culprit. The levelName variable is created on the stack, no memory (on the heap) is allocated for it. The levelName variable and the memory it points to become invalid as soon as the method returns.
Hence when the method leaves this area of memory where levelName points to can be allocated by other parts of the program or other method's stack memory. Whatever is in that area of memory may still be the string, or it may be (partially) overridden by other bits and bytes.
PS: Your exception handling code is …. well it shows a lack of understanding what exception handling does, how to use it and especially when. I hope these are just remnants of trying to get to the bottom of the issue, otherwise get rid of it. I recommend reading a tutorial and introductions on C++ exception handling if you want to continue to use exceptions. Especially something like (map != NULL) should be an assertion, not an exception.
I fixed it.
const char* was to blame.
When returning my map as a char * it worked flawless.
const char *levelFileName = level.attribute("file").value();
char *levelChar = new char[strlen(levelFileName) + 1];
std:: strcpy (levelChar, levelFileName);
return levelChar;
Thats how i now return the map.

Adding an std::string definition causes Access Violation

EDIT: Dear Future Readers, the std::string had nothing to do with the problem. It was an unterminated array.
In a nutshell, the problem is that adding a declaration of a single std::string to a program that otherwise contains only C causes the error "Access violation reading location 0xfffffffffffffffe."
In the code below, if the line where the std::string is declared is commented out, the program runs to completion without error. If the line however is left in the program (uncommented), the program crashes with the above stated Acess Violation error. When I open the running program in the VS2010 debugger, the Access Violation has occurred at the call to ldap_search_sA().
Notice that the declared std::string is never used. It doesn't have to be used for it to cause the access violation. Simply declaring it will cause the Access Violation.
My suspicion is it has nothing to do with the LDAP code, but I could be wrong.
int main()
{
try {
// Uncommenting the next line causes an Access Violation
// at the call to ldap_search_sA().
// std::string s;
LDAP* pLdapConnection = ldap_initA("eu.scor.local", LDAP_PORT);
ULONG version = LDAP_VERSION3;
ldap_set_option(pLdapConnection, LDAP_OPT_PROTOCOL_VERSION, (void*) &version);
ldap_connect(pLdapConnection, NULL);
ldap_bind_sA(pLdapConnection, NULL, NULL, LDAP_AUTH_NTLM);
LDAPMessage* pSearchResult;
PCHAR pMyAttributes[2];
pMyAttributes[0] = "cn";
pMyAttributes[1] = "description";
ldap_search_sA(pLdapConnection, "dc=eu,dc=scor,dc=local", LDAP_SCOPE_SUBTREE, "objectClass=computer)", pMyAttributes, 0, &pSearchResult);
} catch (...) {
printf("exception\n");
}
return 0;
}
PCHAR pMyAttributes[2];
pMyAttributes[0] = "cn";
pMyAttributes[1] = "description";
Attribute array should be NULL-terminated:
PCHAR pMyAttributes[3];
pMyAttributes[0] = "cn";
pMyAttributes[1] = "description";
pMyAttributes[2] = NULL;
I don't know what ldap_search_sA is, but the ldap_search function in
OpenLDAP takes a pointer to a null pointer terminated array of char*.
The array you are passing isn't correctly terminated, so anything may
happen. I'd recommend using std::vector<char*> for this, in general,
and wrapping the calls in a C++ function which systematically postfixes
the terminator, so you don't forget. Although in such simple cases:
char* attributes[] = { "cn", "description", NULL };
will do the trick. It will probably provoke a warning; it really should
be:
char const* attributes[] = { ... };
But the OpenLDAP interface is legacy C, which ignores const, so you'd
need a const_cast at the call site. (Another argument for wrapping
the function.)
Finally, I'd strongly advise that you drop the obfuscating typedefs
like PCHAR; they just make the code less clear.
According to my experience, when weird things like this are observed in C++, what is in fact happening is that some piece of code somewhere corrupts memory, and this corruption may manifest itself in various odd ways, including the possibility that it may not manifest itself at all. These manifestations vary depending on where things are located in memory, so the introduction of a new variable probably causes things to be moved in memory just enough so as to cause a manifestation of the corruption where otherwise it would not be manifested. So, if I were in your shoes I would entirely forget about the string itself and I would concentrate on the rest of the code, trying to figure out exactly what you do in there which corrupts memory.
I notice that you invoke several functions without checking their return values, even though it is not in the spec of these functions to throw exceptions. So, if any of these functions fails, (starting with ldap_initA,) and you proceed assuming that it did not fail, you may get memory corruption. Have you checked this?

C++ Struct initialisation problem

This c++ code is working fine , however memory validator says that I am using a deleted pointer in:
grf->filePath = fname; Do you have any idea why ? Thank you.
Dirloader.h
// Other code
class CDirLoader
{
public:
struct TKnownGRF
{
std::string filePath;
DWORD encodingType;
DWORD userDataLen;
char *userData;
};
// Other Code
CDirLoader();
virtual ~CDirLoader();
Dirloader.cpp
// Other code
void CDirLoader::AddGroupFile(const std::string& _fname)
{
// Other code including std::string fname = _fname;
TKnownGRF *grf = new TKnownGRF;
grf->filePath = fname;
delete grf; // Just for testing purposes
P.S.: This is only an code extract. Of course if I define a struct TKnownGRF inside .cpp and use it as an actual object, gfr.filepath = something, instead of pointer grf->filepath=something, than it is ok, but I do need to have it inside *.h in CDirLoader class, due to many other vector allocations.
Since the function returns void
void CDirLoader::AddGroupFile(const std::string& _fname)
the question is what are you going to do with grf?
Are you going to delete it? If so, then, why do a new? you can just declare a TKnownGRF variable on the stack! In that case, _fname is not contributing to the logic of this method.
I guess that the class CDirLoader has a member variable of type TKnownGRF, say grf_, and that need to be used in the AddsGroupFile() method, e.g.:
grf_.filepath = _fname;
Does this happen to be using an older version of STL, say, VC6, and running multithreaded? Older versions of STL's string class used a reference counted copy on write implementation, which didn't really work in a multithreaded environment. See this KB article on VC 6.
Or, it's also possible that you are looking at the wrong problem. If you call std::string::c_str() and cache the result at all, the cached result would probably be invalidated when you modified the original string. There are a few cases where you can get away with that, but it's very much implementation specific.