Skip to main content
gamedev.net
🔒 Locked

What's wrong?

Started by BradDaBug Jul 27, 2002 at 12:21 PM 3 replies 300+ views
Original Post
BradDaBug
BradDaBug
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?
I like the DARK layout!
mentat
mentat
can you post some code?

hint to post a code nicely: use "source" inside []..
-----------my quote is under construction
BradDaBug
BradDaBug
The infamous "other program":

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

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

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

free(p);

//Close archive

CloseArchive(fp);


And the DLL code for GetDataFromArchive():


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

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

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

if (file->fp == NULL)
return(NULL);


//Copy the file to memory

char *p = NULL;

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


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


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

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

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

fclose(fp);
return(Size);
}


[edited by - BradDaBug on July 27, 2002 1:56:37 PM]
I like the DARK layout!
Grambo
Grambo
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.
--24 Beers in a Case.24 Hours in a Day.Coincedence? I think not!www.gramb0.co.uk
BradDaBug
BradDaBug
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.
I like the DARK layout!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.