开发者

Leak in MiniZip

开发者 https://www.devze.com 2023-01-28 05:17 出处:网络
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 :

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 开发者_JAVA技巧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.


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.


free(s);

(filler to 15 characters)


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号