Online Judge上的C程序运行时错误(问题ID:UVA482),寻求帮助

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

我编写了一个简单的 C 程序来在 Online Judge 上解决 UVA482。程序在本地测试及其他平台运行成功;但是,我在在线法官上遇到运行时错误。

这是我的代码:

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

int main() {
    
    char ch, permute[1001][101], ans[1001][101];
    int i, j, testcases, pos[101];

    scanf("%d", &testcases);

    while (testcases--) {
        
        ch = '\0';
        for (i = 0; ch != '\n'; i++) {
            scanf("%d", &pos[i]);
            ch = getchar();
        }
        
        for (j = 0; j < i; j++) {
            scanf("%s", permute[j]);
        }
          
        for (j = 0; j < i; j++) {
            strcpy(ans[pos[j] - 1], permute[j]);
        }
        for (j = 0; j < i; j++) {
            printf("%s\n", ans[j]);
        }
        if (testcases != 0) {
            printf("\n");
        }
        memset(permute, 0, sizeof(permute));
        memset(ans, 0, sizeof(ans));
        memset(pos, 0, sizeof(pos));

    }
    return 0;
}

有人可以帮助我识别问题或提出运行时错误的其他潜在原因吗?谢谢!

我在 Online Judge 上遇到运行时错误(问题 ID:UVA482)。我在本地进行了测试,使用memset进行内存重置,并保证了编译器的兼容性。预计执行成功,但仍面临问题。任何人都可以帮助找出问题所在吗?谢谢!

c runtime-error
1个回答
0
投票

此行可能存在缓冲区下溢:

strcpy(ans[pos[j] - 1], permute[j]);

如果

pos[j] == 0
,您将访问
ans[-1]
,这当然是未定义的行为。

这就是我测试你的代码所做的:

  • 将代码另存为 Judge.c
  • 使用 gcc 和 google 的地址清理程序编译代码,使用命令
     gcc -o judge judge.c -fsanitize=address -g3
  • 使用一些随机输入运行程序。

我立即从 asan 收到此运行时错误:

==2333519==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffd20ca3f6b at pc 0x7fd597a544bf bp 0x7ffd20c8b1a0 sp 0x7ffd20c8a948
WRITE of size 3 at 0x7ffd20ca3f6b thread T0
12    #0 0x7fd597a544be in __interceptor_strcpy ../../../../src/libsanitizer/asan/asan_interceptors.cpp:440
    #1 0x557ed09605b1 in main /home/al/projects/stackovreflow/judge.c:25
    #2 0x7fd597629d8f in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
    #3 0x7fd597629e3f in __libc_start_main_impl ../csu/libc-start.c:392
    #4 0x557ed09601e4 in _start (/home/al/projects/stackovreflow/judge+0x11e4)

Address 0x7ffd20ca3f6b is located in stack of thread T0 at offset 101803 in frame
    #0 0x557ed09602b8 in main /home/al/projects/stackovreflow/judge.c:5

  This frame has 4 object(s):
    [48, 52) 'testcases' (line 8)
    [64, 468) 'pos' (line 8)
    [544, 101645) 'permute' (line 7)
    [101904, 203005) 'ans' (line 7) <== Memory access at offset 101803 underflows this variable



您可以在此处了解有关 ASAN 以及如何使用它查找运行时错误的更多信息 https://www.cse.unsw.edu.au/~learn/debugging/modules/asan/

© www.soinside.com 2019 - 2024. All rights reserved.