C语言-使用malloc导致的奔溃问题

在使用malloc、memset、free的过程中,出现了程序奔溃,大致现象如下。

image-20210624101400128

image-20210624101425475

程序的实现大致如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void)
{
    int tab_bits = 0, tab_bytes = 0;
    char *compare_zero = NULL;

    tab_bits  = 512;
    tab_bytes = (tab_bits + 7)/8;
    compare_zero = (uint8_t *)malloc(tab_bytes);
    if (NULL == compare_zero)
        return -1;
    memset(compare_zero, 0, tab_bits);
  
    free(compare_zero);

    return 0;
}

通过gdb调试,发现是在free那里奔溃的。然后经过不断的测试,最终发现是memset那里的问题。真是无语啊。

memset的定义如下:

void *memset(void *s, int c, size_t n);
DESCRIPTION:The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.

可以看出,第二个参数c表示的是字节数,而我代码中传入的是位宽,这就导致访问的内存超过了变量compare_zero的内存范围,从而引起了奔溃。

在此记录一下这个失误。

原文地址:https://www.cnblogs.com/mrlayfolk/p/14925738.html