Jump to content
  • Advertisement


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


What's wrong?

This topic is 5988 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

I have a dll creating some data using malloc(). I pass a pointer to the data to another program. Then later the other program calls free() on it. The problem is, it crashes. Why? It''s really simple code, and I don''t know why it could be crashing. Also, the pointer is a char*. When I tell my other program to print the data, it prints it fine, but then there''s some garbage at the end. Any ideas?? Thoughts?

Share this post

Link to post
Share on other sites
The infamous "other program":

    CFile *fp = OpenArchive("woo.txt");

char *p = GetDataFromArchive("woo.txt", fp);

printf("file = %s", p);


//Close archive


And the DLL code for GetDataFromArchive():

char *GetDataFromArchive(char *filename, CFile *file)
//Check our parameters

if ((filename == NULL) || (file == NULL))

//Check and see if our CFile points to an open file

if (file->fp == NULL)

//Copy the file to memory

char *p = NULL;

p = (char*)malloc(GetFilesize(file->Filename));
fread(p, GetFilesize(file->Filename), 1, file->fp);

And in case anyone's curious, GetFilesize():

int GetFilesize(char *filename)
int Size = 0;

FILE *fp = fopen(filename, "rb");
if (fp == NULL)

fseek(fp, 0, SEEK_END);
Size = ftell(fp);


[edited by - BradDaBug on July 27, 2002 1:56:37 PM]

Share this post

Link to post
Share on other sites
Are you sure that the program is crashing when free() is called, because I think it could actually be the FILE* in CFile, because in my experience any attempt to use a FILE* that was not created by the file that is being executed now (example : fopen in exe, currently in dll) will cause a access violation or something similar. Just a thought.

Share this post

Link to post
Share on other sites
After doing away with the GetDataFromArchive() function and replacing it with a ReadFromArchive() that doesn''t allocate the memory, but instead takes a pointer to already allocated memory, it doesn''t crash anymore.

At first I figured I could easily get back a pointer to data that was created in the DLL, since DirectX does it all the time, but apparently if I try to free() it, bad things happen. I thought about putting a function in the DLL to free the created memory, but I decided I''d rather do the memory stuff myself, since I can then allocate memory once and reuse it many times.

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!