reading in file memory problems in vc++ 6

Posted on 2007-07-27
Medium Priority
Last Modified: 2010-04-01
hi, i'm having problems with my program.

i'm reading in a file which contains information which is added into my structure. If i read the file in once it works fine. However if i try and read in the same or another file it crashes giving a user break called from code exception. I also get an access violation if i open a file and then exit the program (whether these are related i'm not sure).

anyway, using break points i tracked the point of the exception being thrown to here

addButton(tHook, tText, tClass, tX, tY, tWidth, tHeight, tAnchor, tProgram, tOutput, tFields);

this method doesn;t get called and according to the debug all the CString vars are filled.  These are global vars that i reuse every time i read a file in.

CString tHook, tClass, tText, tOutput, tProgram;
int tAnchor, tX, tY, tWidth, tHeight;
int tFields[maxFields];

i simply assign the string token to the CString like so                   
tClass = token;

Question by:flynny
  • 4
  • 3
  • 2

Expert Comment

ID: 19581102
hm. could you please give more input?

Especially what type is a token? Are you sure, that you want to overwrite tClass?

Author Comment

ID: 19581137
yes sorry,

the way i read in my files i i read it in a line at a time (i determine this using a terminator ';')

so for example i then have


i then use strtok to split the string using = as a separator.
LPTSTR token;
//get line
token = strtok( line, seps );
if(strcmp(token, "WINDOW") == 0)
token = strtok( NULL, seps );
tClass = token;

yes i will want to overwrite these each time as i copy them into the structure. i just hold these so i can call the addButton method when i have all the variables.  

One thing i forgot to mention also before i read the file in i remove everything from the current structure, using a method initialiseStructure. I have just tried removing this and this seems to sort allow me to open the file again (although it adds everything twice). is there somthing wrong with what i do here?

BOOL initialiseStructure()

      int i;
      for(i=0; i<maxHooks; i++)
            if(hookFile.hooks[i] == NULL)

            int j;
            for(j=0; j<maxButtons; j++)
                  if(hookFile.hooks[i]->buttons[j] == NULL)

                  hookFile.hooks[i]->buttons[j]->dimensions->x = NULL;
                  hookFile.hooks[i]->buttons[j]->dimensions->y = NULL;
                  hookFile.hooks[i]->buttons[j]->dimensions->width = NULL;
                  hookFile.hooks[i]->buttons[j]->dimensions->height = NULL;
                  hookFile.hooks[i]->buttons[j]->dimensions->anchor = NULL;

                  int k;
                  for(k=0; k<maxFields; k++)
                        if(hookFile.hooks[i]->buttons[j]->fields[k] == NULL)




      return true;
LVL 22

Expert Comment

ID: 19581251
first thing,  GlobalFree() is probably the wrong thing to call.  That's an old windows 3.1  API.

If you allocated a node with a C++ "new", you should  use the corresponding C++ "delete".

If you allocated memory with "malloc", you should call "free".

Also it looks like you're generating pointers with strtok().  Don't try freeing those pointers!   They're not pointing to anything that was allocated on the heap, so these free's are going to blow up.

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Accepted Solution

cruxy earned 1000 total points
ID: 19581274
first of all an assingment from a LPTSTR to a CString is problematic - LPTSTR is either a char * or a wchar *; CString is an object with an inner buffer.
LPCTSTR could be directly casted to a CString and the other way round; an LPCTSTR is a const cchar * or const wchar *
So if you want to assign a LPTSTR to a CString I'd do a modification with the internal buffer of the CString - refer to http://msdn2.microsoft.com/en-us/library/ms928943.aspx

The biggest problem IMO is, that those two pointers assigned are also of a different scope. So tClass is global and token local - that would cause a crash on exit in any case.

Author Comment

ID: 19581299
hi thanks for the reply.

i'm using globalalloc to allocate the memory for each item e.g.

            BUTTON *pBut = (BUTTON*) GlobalAlloc(GPTR, sizeof(BUTTON));

            HGLOBAL memPtr = GlobalAlloc(GMEM_FIXED, strlen(bClass)+1); //pointer to mem block

            if( memPtr && (pBut->bClass = (LPTSTR)GlobalLock(memPtr)) != NULL )
                  RtlMoveMemory(pBut->bClass, bClass, strlen(bClass)+1);
                  char buf[128];
                  sprintf(buf, "Error Unable to allocate Memory for button class.");
                  MessageBox(NULL, buf, NULL, 0);

also this is how i read my line before i use strtok

                  ch = fgetc(fr);
                  charCount = 0; //reset

                  while(ch != ';') //read to find out what the type is
                        line[charCount] = ch;

                        ch = fgetc(fr);

                        if(charCount > lineSize)
                              return -5;

                        if(ch == EOF)
                              return 0; //read ok

                  line[charCount] = '\0';
also regards the pointers should i simply set these to null?

many thanks

Author Comment

ID: 19581347
hi bu changing the GlobalFree(ptr) to just setting them to NULL solved this problem.

However the other problem with the access violation on after i open a file and then close the program still arises. it then points to this line

1020E761   mov         dword ptr [ecx],edx

does this look like it is something to do with not cleaning the mem up?
LVL 22

Expert Comment

ID: 19581354
You should not be allocating objects, if that's what bClass is, with anything other than the C++ "new"!!  

Author Comment

ID: 19581430
ok the problem is i need other objects in the process to see these objects, will that still be the case with new?

so rather than

BUTTON *pBut = (BUTTON*) GlobalAlloc(GPTR, sizeof(BUTTON));


BUTTON *pBut = new BUTTON();

suffice? then can i simply assign the CStrings to the variables in the structure?
many thanks matt

Expert Comment

ID: 19581674
the new would allocate the object as it should happen, so calling the constructor.
this has nothing todo with the CString problematic. cause a CString is only direct castable as a LPCTSTR; you need a LPTSTR instead, so you should call tClass.getBuffer(strlen(token)+1) then copy over the string from token with strcpy() and then calling tClass.ReleaseBuffer() after that point the buffer is only accessible via the tclass methods; the pointer got with getBuffer should not be used anymore.

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question