AddressSanitiser:SEGV在未知地址

时间:2018-04-12 10:27:40

标签: c runtime-error fgets sigsegv

我收到错误

  

未知地址的SEGV

在运行我的程序时。我很确定它来自fgets(),但我不太清楚为什么。在此之前,我正在使用scanf()并且它工作正常。输入正好进入数组,但是我必须使用fgets()来检测新行的输入。任何人都可以帮助我理解为什么我收到此错误并建议一种方法来解决这个问题?

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

int main(void) {

    int x = -1;
    int y = -1;

    scanf("%d %d", &x, &y);

    if (x <= 0 || y <= 0) {
        printf("Cannot decode\n");
        return 1;
    }

    char *temp = 0;
    int v[x][y];

    for (int t=0; t < y; t++) {
        for(int i=0; i < x; i++) {

            if (fgets(temp, x, stdin)) {
                v[i][t] = atoi(temp);
            }
        }
    }

    // To test array
    int c, o;
    for(o=0; o < x; o++) {
        for(c=0; c < y; c++) {
            printf("%d", v[c][o]);

        }
        printf("\n");
    }

    return 0;
}

错误代码:

ASAN:DEADLYSIGNAL
=================================================================
==19==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x7fcaaf49d4ab bp 0x
000000000001 sp 0x7ffc84b842b8 T0)
==19==The signal is caused by a WRITE memory access.
==19==Hint: address points to the zero page.
#0 0x7fcaaf49d4aa in __memmove_avx_unaligned_erms (/usr/lib/libc.so.6+0x1574aa)
#1 0x7fcaaf3b4708 in __GI__IO_getline_info (/usr/lib/libc.so.6+0x6e708)
#2 0x7fcaaf3b353c in fgets (/usr/lib/libc.so.6+0x6d53c)
#3 0x5001f4 in main /home/nonogram.c:39:11
#4 0x7fcaaf366f49 in __libc_start_main (/usr/lib/libc.so.6+0x20f49)
#5 0x4187d9 in _start (/home/nonogram+0x4187d9)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV (/usr/lib/libc.so.6+0x1574aa) in __memmove_avx_unaligned_erms
==19==ABORTING

1 个答案:

答案 0 :(得分:0)

您必须分配内存来存储您正在阅读的信息。使用callocmalloctemp指针保留内存。

char *temp = calloc(length_you_expect, sizeof(char))

而不是:

char *temp = 0

请记住在使用它后自由:

free(temp)