Reputation: 11439
I'm using MiniZip to unzip a file in an iPhone project. Everything works fine but i get a leak in instruments in the MiniZip code on this line :
unzip.c line 493
s=(unz_s*)ALLOC(sizeof(unz_s));
*s=us;
unzGoToFirstFile((unzFile)s);
return (unzFile)s;
I understand that the var allocated with ALLOC is returned and not deallocated. In objective-C i would simply do an autorelease, but how can i achieve that in plain C ?
Thanks, Vincent.
Upvotes: 1
Views: 935
Reputation: 11
unzOpen() is intended to allocate and return a handle s to the caller. After you got that handle you may operate on this zip-archive (i.e. search for a file, inflate files from archive, ...). After all operations are finished, you have to explicitiely close zip-archive by calling unzClose(s) which de-allocates s for you.
Here is an example to extract a specific file from an archive:
unzFile hArchive;
unsigned char buffer[1024];
hArchive = unzOpen("abc.zip");
if (hArchive != NULL) {
if (unzLocateFile(hArchiveFile, "example.txt", 0) == UNZ_OK) {
if (unzOpenCurrentFile(hArchiveFile) == UNZ_OK) {
while (unzReadCurrentFile(hArchiveFile,buffer,sizeof(buffer)) > 0) {
/* write buffer to another file / to stdout / ... */
}
unzCloseCurrentFile((unzFile) *hArchiveFile);
}
}
}
unzClose(hArchive);
see http://www.winimage.com/zLibDll/minizip.html for further information.
Upvotes: 1
Reputation: 215547
Whatever function this is in, the problem is not in that function. It's supposed to return an allocated object, not uselessly allocate-and-free before returning. The problem is in your use of the library. You're never calling the function to free the pointer you obtained from calling this function.
Upvotes: 0
Reputation: 64128
The caller of that method is responsible for s
and must free()
it when it is no longer required to avoid the memory leak. This is the convention in C.
You would have to tie in a 3rd-party GC library, perhaps something like Hans Boehm's GC for C/C++. However, my suggestion would be to just free the memory when it is appropriate on your own. You'll run into less hassles that way.
Upvotes: 2