Archived

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

BradDaBug

What's wrong?

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);

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]

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