2012-07-31 42 views
7

我看到的valgrind分类内存泄漏到:Valgrind的合法 “可能失去” 字节例如

  • 肯定失去
  • 间接失去
  • 可能失去
  • 仍可达
  • 抑制

我只是修正了一个泄漏,其中“可能丢失”是主要问题。

documentation says:“可能失去意味着你的程序正在泄漏内存,除非你正在做不寻常的事情有可能导致它们指向到一个分配块的中间指针;请参阅用户手册一些可能导致

我可以请一个例子”做指示,可能会导致他们指向分配块中间“的不寻常的事情吗?

我的意思是一个例子,其中“可能丢失”可以忽略,虽然它是由valgrind报告的。其中,使用指针使得Valgrind的一个例子抱怨,但在同一时间以这种方式使用的指针是某种合法

谢谢

回答

7

哪些文件是不同的库一些例子是有它们自己的分配器,并且返回的内存不是直接由底层OS分配器(malloc/sbrk)返回的指针,而是偏移后的指针。例如,考虑一个获得一些额外内存和存储元信息的分配器(可能是垃圾收集器的类型信息)。分配和释放的过程将类似于:

void* allocate(size_t size) { 
    metainfo_t *m = (metainfo_t*) malloc(size + sizeof(metainfo)); 
    m->data = some_value; 
    return (void*)(m+1);   // [1] 
} 
void deallocate(void* p) { 
    metainfo_t *m = ((metainfo_t*)p) - 1; 
    // use data 
} 
void * memory = allocate(10); 

当Valgrind是跟踪的内存,它会记住,是由malloc返回原来的指针,该指针不存储在程序中。但这并不意味着内存已经泄漏,只是意味着指针不能直接在程序中使用。特别是memory仍然保存着返回的指针,并且可以调用deallocate来释放它,但valgrind在程序中的任何位置都看不到原始返回的指针,位置(char*)memory - sizeof(metadata_t)并发出警告。

5
char *p = malloc(100); 
if (p != 0) 
{ 
    p += 50; 
    /* at this point, no pointer points to the start of the allocated memory */ 
    /* however, it is still accessible */ 
    for (int i = -50; i != 50; i++) 
     p[i] = 1; 
    free (p - 50); 
} 
2
char *p = malloc(100); 
if (p != 0) 
{ 
    p += 50; 
    /* at this point, no pointer points to the start of the allocated memory */ 
    /* however, it is still accessible */ 
    for (int i = -50; i != 50; i++) 
     p[i] = 1; 
    free (p - 50); 
} 

因为它看起来很有趣,所以我确实运行了代码并且valgrind它。结果如下。

[email protected]:~$ valgrind test 
==14735== Memcheck, a memory error detector 
==14735== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al. 
==14735== Using Valgrind-3.6.1-Debian and LibVEX; rerun with -h for copyright info 
==14735== Command: test 
==14735== 
==14735== 
==14735== HEAP SUMMARY: 
==14735==  in use at exit: 0 bytes in 0 blocks 
==14735== total heap usage: 32 allocs, 32 frees, 2,017 bytes allocated 
==14735== 
==14735== All heap blocks were freed -- no leaks are possible 
==14735== 
==14735== For counts of detected and suppressed errors, rerun with: -v 
==14735== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 6) 

它说没有泄漏是可能的。我错过了什么?

+0

请将评论作为评论,而不是答案。 StackOverflow通知用户对他们答案的评论,但不会(也不应该)通知也回答同一问题的其他用户的用户。这说... – hvd 2012-07-31 14:17:42

+0

...代码最终释放了内存,所以valgrind没有看到它。我所做的一点是,如果程序在到达'free'之前退出(或者完全没有释放),并且'p'保持设置,那么valgrind会认为分配的内存可能会丢失。在测试时,为了让“p”保持设置,您可能还需要将“p”设置为全局。 – hvd 2012-07-31 14:20:09

+0

我试图发表评论,但评论有字符数限制。对于那个很抱歉。 – jaeyong 2012-08-01 00:42:28