2015-11-17 28 views
0

我正在閱讀git的源代碼。我列舉了這個xmalloc的實現。xmalloc中毒的目的是什麼

static void *do_xmalloc(size_t size, int gentle) 
{ 
    void *ret; 

    if (memory_limit_check(size, gentle)) 
     return NULL; 
    ret = malloc(size); 
    if (!ret && !size) 
     ret = malloc(1); 
    if (!ret) { 
     try_to_free_routine(size); 
     ret = malloc(size); 
     if (!ret && !size) 
      ret = malloc(1); 
     if (!ret) { 
      if (!gentle) 
       die("Out of memory, malloc failed (tried to allocate %lu bytes)", 
        (unsigned long)size); 
      else { 
       error("Out of memory, malloc failed (tried to allocate %lu bytes)", 
         (unsigned long)size); 
       return NULL; 
      } 
     } 
    } 
#ifdef XMALLOC_POISON 
    memset(ret, 0xA5, size); 
#endif 
    return ret; 
} 

我想知道這是什麼部分的目的:

#ifdef XMALLOC_POISON 
    memset(ret, 0xA5, size); 
#endif 
+0

診斷分配後實際寫入哪部分分配的空間? –

回答

1

這是一種能夠方便地看到,如果你正在使用未初始化的內存。如果你使用內存和內容全部(或大部分)是0xA5那麼你知道內存還沒有被初始化,並且你有未定義的行爲。

1

如果定義了宏XMALLOC_POISON,該函數不僅會分配內存,還會將內存中的值初始化爲(似乎是)任意垃圾值。在調試由未初始化的變量引起的問題時,這可能是一種有用的技術。