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的内存范围,从而引起了奔溃。

在此记录一下这个失误。

---------------------------------- 2021.07.23 ---------------------------------

补充,再次遇到了内存崩溃的问题,这里进行补充。

示例一:memcpy越界,错误的代码大致如下

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

#define BITS2BYTES(x)  (((x) + 7) / 8)
#define BITS2WORDS(x)  (((x) + 31) / 32)

int main(void)
{
    int bits = 128;
    char  *buf_orignal = NULL;
    unsigned int *buf_dest = NULL;

    buf_orignal = (char *)malloc(BITS2BYTES(bits));
    memset(buf_orignal, 0, BITS2BYTES(bits));

    buf_dest = (unsigned int *)malloc(BITS2WORDS(bits));
    memset(buf_dest, 0, BITS2WORDS(bits));
    
    memcpy(buf_dest, buf_orignal, BITS2BYTES(bits));
    
    return 0;
}

上述代码中buf_orignal分配的内存大小为128/8=16字节,而buf_dest分配的大小为128/32=4(分配内存之后强制转换为unsigned int*,但内存大小还是4),使用memcpy从buf_orignal拷贝了16字节到buf_dest中,将发生内存越界(部分环境程序可能不会奔溃)。

posted @ 2021-06-24 10:23  zhengcixi  阅读(2238)  评论(0编辑  收藏  举报
回到顶部