Archived

This topic is now archived and is closed to further replies.

Malloc error

This topic is 5570 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello! Im having some trouble with malloc. I run WindowsXP and MSVC 6.0. This following line causes my program to crash:
      
texture->imageData=(GLubyte *)malloc(imageSize);	



- imageSize = 65536
- GLubyte is defined as "unsigned char" (not that it should matter though)
- imageData is a GLubyte pointer
  
Could this be an error in MSVC's malloc function? I have no idea of how to fix this. I have pinpointed the line that causes the crash and printed out the variable values. The strange thing is that it only crashes when i run the program without a debugging enviroment. / The program is COMPILED in DEBUG MODE in both cases. / When I run the program in MSVC's debug enviroment, it runs fine. / When I execute the exe-file in any other way it crashes (Ctrl+F5 or Explorer). I have rebuild everyting about 10 times and im sure im running the right exe-file. Crash information:
  
AppName: cn.exe	 AppVer: 0.0.0.0	 ModName: ntdll.dll
ModVer: 5.1.2600.0	 Offset: 000036f7
  
The program error:
  
The instruction at "0x77f536f7" referred to the memory at "0x00000000". The memory operation could not be executed.
The following error was returned:
The memory could not be "written".
  
Thank you for your time. /Fredrik Olsson [edited by - FXO on September 8, 2002 11:30:53 PM]

Share this post


Link to post
Share on other sites
I believe that in some part your program are writing to the wrong memory address, maybe you alloc some number of bytes, but are writing more than the allocated number.
Or maybe the "texture" is pointing to the wrong address or are NULL.

Share this post


Link to post
Share on other sites
Are you refering/opening/loading some files using relative path before that codes? If so, it might caused by the path thingie. Change it to absolute path and see. Try using GetLastError and FormatMessage to see what''s your error.

Just my suggestion.

Share this post


Link to post
Share on other sites
crash on malloc? 97% of the time that means somewhere previous in your program in corrupting memory. Here''s why. the malloc function uses a table of data to manage where memory is allocated and how much, and the only reaosn aa call to malloc will crash is because that table is being corrupted. In debug mode, the table is stored differently than in release mode, and it''s pretty common in my experience for memory corruption to sneak past Visual C''s pretty loust CRT Debug libraries and then only show up in release mode, where CRT debug stuff isn''t present.

(CRT is the memchecking stuff used by default in debug mode-- it''s supposed to generate assert() errors if you overwrite memory).

Also! Check for accidentally using free(ptr) on either a NULL pointer or a pointer you''ve already free''d. That was usually the main culprit for cauing malloc to crash in my experience.

- Air

Share this post


Link to post
Share on other sites
Thank you for your input!

DerekSaw: Yes, the relative paths are cluttered all over the place, I changed the onces close to the malloc()-statement, but it didnt help.
I couldn''t get the GetLastError()/FormatMessage() working, I''ll have to read up on which parameters to parse. Where should I put it?

lytlea: Im going through all the calls to loadTGA(), and there are a few .
I have found one class that has __vfptr=0x0000000, but none have a "NULL" this-pointer.

Air: I found a call to free() with a NULL pointer (I used a macro to check all.

daerid: Shouldn''t malloc work? I have quite a few lines to replace, my project is spread over 192 files.



-Im not recompiling the exe, its a debug build, are the malloc table still stored differently when run under MSVC debug enviroment and from explorer?

-__vfptr is a pointer to a class virtual functions, right?
My "material"-class, which calls loadTGA() sometimes has a NULL _vfptr, could this be right?

Share this post


Link to post
Share on other sites
Ok, if I understand your response to my suggestion correctly, youd don''t need to check every single call to LoadTGA - just the one that''s causing the crash. If the function is called many times in your program, don''t set the breakpoint inside the function, set it on the function call itself. Then use MSVCs debugger to ''step-into'' the function and check your values. See if anything is out of whack.

However, the other suggestions people have been giving about corrupted memory are probably more likely. Try checking your last few memory allocations before the crash. See if anything is bogus there.

And if you are using C++, it is better to use new. Malloc ''will'' work, but the biggest reason (from my limited knowledge), is that malloc doesn''t understand constructors. Also, you can pass delete a NULL pointer and it won''t crash hard like free(). Plus you can create your own new handler easily for debugging purposes.

Share this post


Link to post
Share on other sites
Im getting the same error when trying to start ICQ..
Could it have anything to do with my programs error, or is
"the memory could not be written" in "NTDLL.DLL" a general error?

Share this post


Link to post
Share on other sites
quote:
Original post by FXO
Yes, the relative paths are cluttered all over the place, I changed the onces close to the malloc()-statement, but it didnt help.
I couldn''t get the GetLastError()/FormatMessage() working, I''ll have to read up on which parameters to parse. Where should I put it?


If you are using exception, that''s the better. Put it under any catch(). And wow, 192 files! I bet you are using exceptions.

Share this post


Link to post
Share on other sites
quote:
Ok, what about the __vfptr being NULL, isnt that anything to worry about?


The C malloc function will not set up the virtual function table pointer. Do not use it to allocate classes that contain virtual functions. The operators new and delete will handle this correctly.

And they look better, too.


  
texture->imageData = new GLubyte [imageSize];

Share this post


Link to post
Share on other sites
DerekSaw: Hmm, what do you call an exception?,
I use my own like this: if(x) Sys_Error("Error Message")

null_pointer: Doh! I''m guilty, didn''t know that.
Im using my own memory allocator.

alvaro: ok, will free crash when I free freed pointers to?


-Is there anyway to write your own memory-allocator so it will automatically handle the setting of virtual function pointers?
Because I want the class allocated in a memory segment allocated by my memory-handler..

Thanks!

Share this post


Link to post
Share on other sites
Yes, you can use placement new and an implicit destructor call, both of which do no actual memory allocation. They just handle all the messy class stuff automatically. Example below:


  
# include <iostream>
# include <new> // for placement new


using std::cout;
using std::endl;

class my_class
{
public:
virtual void function () { cout << "hello" << endl; }
};

int main ()
{
char memory [sizeof (my_class)];

// invoke the constructor on existing memory:


my_class* p = new (memory) my_class;

// call a virtual function just to verify everything:


p->function ();

// invoke the destructor, this won't happen automatically:


p->~my_class ();
}


Keep in mind that the expression new (memory) my_class; is not actually a cast. You are passing the address (named memory) here to the placement operator new. You should be able to find more information about providing custom versions of operator new by searching on google.

[edited by - null_pointer on September 10, 2002 8:55:40 PM]

Share this post


Link to post
Share on other sites
quote:
DerekSaw: Hmm, what do you call an exception?, I use my own like this: if(x) Sys_Error("Error Message")


Exceptions are a new facility in C++. They are more like a longjmp controlled by language rules. A function that encounters an error can "throw" an exception. This action "reverses" program flow and "unwinds" the stack until it hits the appropriate "catch" handler.

Example:


    
# include <exception>
# include <iostream>

using std::cout;
using std::endl;
using std::exception;

void function ()
{
throw exception ("function threw an exception!");

cout << "la la la" << endl; // <- never executes

}

int main ()
{
try
{
function ();

cout << "la la la" << endl; // <- never executes

}

catch (exception& e)
{
cout << e.what () << endl;
}
}


Normally one would only throw an exception on an error condition. Exactly which types of errors constitute exceptions always causes a large debate, but most agree that unpredictable show-stopping problems are good reasons for throwing an exception.

Exceptions support a few more features, like filtering, rethrowing, exception specifications, etc. The most important thing is that when properly used they can 1) cut down on the amount of code you have to write and 2) more clearly separate the error-handling code from the normal code.

A forum search should reveal more information, and I believe there are a few articles on GameDev about using C++ exceptions.

[edited by - null_pointer on September 10, 2002 9:18:41 PM]

Share this post


Link to post
Share on other sites
Here's some simple exception thingie:

    
void SomeFunc()
{
...
if (!DoSomeThing())
throw "DoSomething() fail in SomeFunc().";

// just an example:

HWND hwnd = ::CreateWindowEx(...);
if (hwnd == 0)
throw ::GetLastError();
...
}
int main(...)
{
try
{
...
SomeFunc();
cout << "Completed!" << endl;
return 0;
}
catch(int errorCode)
{
TCHAR *msg;
::FormatMessage(...);
::MessageBox(...);
::LocalFree(msg);
return 3;
}
catch(const char *msg)
{
cerr << "Error: " << msg << endl;
return 3;
}
catch(...)
{
cerr << "Unknown exception caught." << endl;
return 2;
}
return 1;
}

If DoSomeThing() returns 0, then an exception is thrown. And the nearest try/catch block will caught it and jumps to the matching catch() block. ... also the failure of CreateWindowEx(), the code above will throw an integer (GetLastError) and got caught under the catch(int) block. Cool isn't it? ... and with GetLastError() and FormatMessage(), the error message could be more informative.

btw, use new/delete in your C++. If you want your customized allocation, overload them. Search for "Placement New"

Hope you got the idea. Good luck.

[EDIT] oops. Fix some error. And oh... null_pointer is damn fast.

[edited by - DerekSaw on September 10, 2002 9:26:03 PM]

Share this post


Link to post
Share on other sites
Using throw as exception catcher, seems neat, thanks for the tip

Overloading new and delete is probably what I wanna do, gonna look into that.

Thanks guys, you have helped me alot!

Share this post


Link to post
Share on other sites