我正在编写一个wireshark 解剖器并遇到奇怪的内存管理问题。我有以下功能:
guint8* foo_hex2bytes(guchar *str, guint len){
...
//allocate memory for the result and start converting
res = (guint8*)wmem_alloc(scope, sizeof(guint8)*((len>>1)));
for(i=0; i<(len>>1); i++){
//check that the two digits under question are HEX digits
if(!isxdigit(*(str+2*i)) || !isxdigit(*(str+2*i+1))){
wmem_free(scope, res);
return NULL;
}
//append the byte
sscanf((const char*)(str+2*i), "%02x", &res[i]);
}
return res;
}
此函数用于多个地方(proto_reg_hanoff_foo
以及dissect_foo
),因此我不会将结果分配给任何特定的池。
在我的 proto_reg_handoff_foo
我得到函数的返回值,将它复制到另一个内存位置并释放原始结果:
...
if(syskey_str && strlen(syskey_str)){
wmem_free(wmem_epan_scope(), syskey_bytes);
if(tmp = foo_hex2bytes((guchar*)syskey_str, (guint) strlen(syskey_str))){
syskey_len = (guint)strlen(syskey_str)>>1;
syskey_bytes = (guint8*)wmem_alloc(wmem_epan_scope(), strlen(syskey_str)>>1);
memcpy(syskey_bytes, tmp, strlen(syskey_str)>>1);
wmem_free(NULL, tmp);
}
}
...
奇怪的是,我得到了一个窗口触发的断点(或调试器之外的普通崩溃)wmem_free(NULL, tmp)
。除了错误发生在wmem_core.c:72
.
注意我已经修改我foo_hex2bytes
的接受第三个wmem_allocator_t
参数并简单地传递wmem_epan_scope()
(或wmem_packet_scope()
在适当的情况下) - 这会在应用程序关闭时导致类似的崩溃。我也尝试过使用malloc()
并手动清除所有内存(有时会起作用,有时null pointer
即使应用程序只使用 14K 内存并且还有更多可用内存也会返回)。
编辑:问题似乎存在sscanf(...)
- 我没有分配足够的内存并且它已经溢出。通过增加分配大小来修复。