gpt4 book ai didi

c - 在 Windows 上的 ubuntu 中使用 gdb 时段错误消失

转载 作者:太空宇宙 更新时间:2023-11-04 10:10:30 25 4
gpt4 key购买 nike

我的任务是找出以下代码中的错误并修复它:

/* $Id: count-words.c 858 2010-02-21 10:26:22Z tolpin $ */

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

/* return string "word" if the count is 1 or "words" otherwise */
char *words(int count) {
char *words = "words";
if(count==1)
words[strlen(words)-1] = '\0';
return words;
}

/* print a message reportint the number of words */
int print_word_count(char **argv) {
int count = 0;
char **a = argv;
while(*(a++))
++count;
printf("The sentence contains %d %s.\n", count, words(count));
return count;
}

/* print the number of words in the command line and return the number as the exit code */
int main(int argc, char **argv) {
return print_word_count(argv+1);
}

除了一个单词外,该程序对于给定的所有单词都运行良好。使用 ./count-words hey 运行它会导致段错误。

我在 Windows 10 上的 Linux 子系统上运行我的代码(这就是我所知道的,它至少被称为......),使用官方的 Ubuntu 应用程序。

当从终端运行程序时,我确实遇到了段错误,但是使用 gdb,由于某种原因程序运行正常:

(gdb) r hey
Starting program: .../Task 0/count-words hey
The sentence contains 1 word.
[Inferior 1 (process 87) exited with code 01]
(gdb)

在第 9 行添加断点并单步执行代码后,我得到了这个:

(gdb) b 9
Breakpoint 1 at 0x400579: file count-words.c, line 9.
(gdb) r hey
Starting program: /mnt/c/Users/tfrei/Google Drive/BGU/Semester F/Computer Architecture/Labs/Lab 2/Task 0/count-words hey

Breakpoint 1, words (count=1) at count-words.c:9
9 if(count==1)
(gdb) s
10 words[strlen(words)-1] = '\0';
(gdb) s
strlen () at ../sysdeps/x86_64/strlen.S:66
66 ../sysdeps/x86_64/strlen.S: No such file or directory.
(gdb) s
67 in ../sysdeps/x86_64/strlen.S
(gdb) s
68 in ../sysdeps/x86_64/strlen.S
(gdb)

奇怪的是,当我从“真正的”Ubuntu(在 Windows 10 上使用虚拟机)运行同样的东西时,段错误确实发生在 gdb 上。

我倾向于认为这与我的运行时环境(“Windows 上的 Ubuntu”相关)有某种关系,但找不到任何对我有帮助的东西。

这是我的生成文件:

all: 
gcc -g -Wall -o count-words count-words.c

clean:
rm -f count-words

提前致谢

最佳答案

I'm asking why it didn't happen with gdb

当 GDB 在真实(或虚拟)UNIX 系统上运行时,它确实发生了。

在奇怪的“Windows 上的 Ubuntu”环境下运行时并没有发生,因为那个环境正在做疯狂的事情。特别是,出于某种原因,Windows 子系统通常将只读部分(.rodata,可能还有 .text)映射为具有可写权限(这就是程序不再崩溃的原因) ),但仅当您在调试器下运行程序时。

我不知道为什么 Windows 会那样做。

请注意,调试器确实需要写入(只读).text 部分以插入断点。在真实的 UNIX 系统上,这是通过 ptrace(PTRACE_POKETEXT, ...) 系统调用实现的,该系统调用更新只读页面,但将其保留为只读以用于下级(被调试)过程。

我猜测 Windows 无法完美地模拟此行为(特别是在更新页面后不会对页面进行写保护)。

附言一般来说,使用“Windows 上的 Ubuntu”来学习 Ubuntu 会充满像这样的问题。使用虚拟机可能会更好。

关于c - 在 Windows 上的 ubuntu 中使用 gdb 时段错误消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49396598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com