我正在实现我自己的malloc()函数,并且在测试它时,我一直遇到缓冲区溢出错误,而我不太知道为什么,它是在while循环中指定的。

问题描述 投票:0回答:1
mymalloc

撞了缓冲区的溢出,因为while循环允许

current
走过堆的末端。 4096-Byte跳入
current->size

意味着它正在阅读垃圾,这可能是由于过度付出的。

为什么它发生
c while-loop malloc buffer-overflow
1个回答
0
投票

循环检查

heap.bytes + MEMLENGTH
((char *)current + current->size) <= end
,但是如果
current->size
是巨大的(例如4096,来自非初始化的内存),则逐渐远。
堆中没有清晰的“末端”标记,让
current

逃脱。

fix

tonge the the Loop并添加安全检查:
  • while (current < end && current->size > 0) { if (current->allocated == 0 && current->size >= bytesToAlloc) { if (current->size > bytesToAlloc) { split_chunk(current, bytesToAlloc); } current->allocated = 1; return (void *)((char *)current + sizeof(header)); } current = (header *)((char *)current + current->size); if ((char *)current > (char *)end) break; // Stop if we overshoot }
    检查
    
    确保正确设置了块(例如,一大块
  • initialize_heap()
  • )。
    如果是4096,则崩溃是从读取到末端的读数。
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.