【发布时间】:2021-01-22 02:40:26
【问题描述】:
世界!我不擅长动态内存分配,所以请帮助我!问题是当我在没有消毒剂的情况下编译 c 文件时,它可以正常执行。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *str = (char *)malloc(sizeof(char));
int i = 1;
while (str[i - 2] != '\n')
{
str = (char *)realloc(str, i * sizeof(char));
str[i - 1] = getchar();
i++;
}
str[++i] = '\0';
fputs(str, stdout);
free(str);
return 0;
}
这里是消毒剂所说的:
==7174==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60200000000f at pc 0x55739456b340 bp 0x7fffba0090f0 sp 0x7fffba0090e0
READ of size 1 at 0x60200000000f thread T0
#0 0x55739456b33f in main (/home/bek/diff1+0x133f)
#1 0x7fd15ff780b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
#2 0x55739456b1ad in _start (/home/bek/diff1+0x11ad)
0x60200000000f is located 1 bytes to the left of 1-byte region [0x602000000010,0x602000000011)
allocated by thread T0 here:
#0 0x7fd160250bc8 in malloc (/lib/x86_64-linux-gnu/libasan.so.5+0x10dbc8)
#1 0x55739456b27e in main (/home/bek/diff1+0x127e)
#2 0x7fd15ff780b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
SUMMARY: AddressSanitizer: heap-buffer-overflow (/home/bek/diff1+0x133f) in main
【问题讨论】:
-
总是为缓冲区重新分配一个字节似乎相当低效。您可能需要先重新考虑这种方法。
-
您可能需要
char c = getchar(); if(c == '\n') break;之类的东西来避免@SouravGhosh 发现的有问题的if 语句。 -
@AKX
int c:D -
@AnttiHaapala 当然,忘记了
DreEOF。
标签: arrays c pointers dynamic-memory-allocation