【问题标题】:Random Bytes In C OutputC 输出中的随机字节
【发布时间】:2019-12-17 15:10:03
【问题描述】:

我刚刚用 C 语言编写了我的第一个程序,它是一个剖宫产实现。它在短输入的情况下按预期工作,但有时会在输出的 和 处产生看似随机的字节,我不知道为什么。

我曾尝试查看 GDB 中的程序,但还没有足够的经验来弄清楚到底出了什么问题。我很想知道如何使用像 GDB 这样的调试器来解决这个问题。

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

void rot(char*, int);

char alphabet[27] = "abcdefghijklmnopqrstuvwxyz";

int main (int argc, char* argv[]) {
    if (argc != 3) {
        printf("Usage: %s [lowercase-text] [rotation-number]\n", argv[0]);
        return 1;
    } else {
        rot(argv[1], atoi(argv[2]));
    }
}


void rot (char* t, int r) {
    char result[100];
    for (int i = 0; i < strlen(t); i++) {
        char* location = strchr(alphabet, t[i]);
        result[i] = location ? alphabet[(location - alphabet + r) % strlen(alphabet)] : t[i];
    }
    printf("%s\n", result);
}

这是意外的输出。实际的旋转工作正常,但最后有一些意想不到的字节。

michael@linux:~/Desktop$ ./rotation 
Usage: ./rotation [lowercase-text] [rotation-number]
michael@linux:~/Desktop$ ./rotation rotations_are_cool 13
ebgngvbaf_ner_pbby��� (<- Why are these here ???)

这是我对 GDB 的尝试。最后我无法识别额外的数据标记。 (完整输出@https://pastebin.com/uhWnj17e

(gdb) break *rot+260
Breakpoint 1 at 0x936: file ../rot.c, line 25.
(gdb) r rotations_are_cool 13
Starting program: /home/michael/Desktop/rotation rotations_are_cool 13

Breakpoint 1, 0x0000555555554936 in rot (
    t=0x7fffffffe2d2 "rotations_are_cool", r=13) at ../rot.c:25
25      printf("%s\n", result);
(gdb) x/s $rbp-0x80
0x7fffffffdde0: "ebgngvbaf_ner_pbby\377\367\377\177"

这种奇怪的情况只发生在大约 50% 的时间里,而且在字符串较长时发生的频率更高。请帮助解释并消除这一点。任何其他可以改进我的代码的技巧也值得赞赏。谢谢一打!

【问题讨论】:

  • 你的字符串不是空终止的。
  • @Retired-Ninja 我尝试在 for 循环之后添加类似 result[strlen(result)] = NULL 的内容,但似乎没有任何区别
  • 那是因为 strlen 需要您尝试提供的 nul 终止符 :( 在 printf 之前添加 result[i] = '\0';
  • 哦,好的,然后在循环之前在同一范围内定义i。它在下面的答案中......
  • @WeatherVane 有效。非常感谢!

标签: c pointers argv stdio strchr


【解决方案1】:

字符串的结尾由字符'\0'识别。

所以你可以这样做

    char result[100];
    int i;
    for (i = 0; i < strlen(t); i++) {
        char* location = strchr(alphabet, t[i]);
        result[i] = location ? alphabet[(location - alphabet + r) % strlen(alphabet)] : t[i];
    }
    result[i] = '\0';

你也没有检查,result 对字符串来说足够大,所以你可以动态分配所需的内存

    size_t len = strlen(t)
    char *result = malloc(len + 1); /* +1 for terminating '\0' character */
    if(result == NULL) {
        /* Error allocating memory */
    }
    int i;
    for (i = 0; i < len; i++) {
        char* location = strchr(alphabet, t[i]);
        result[i] = location ? alphabet[(location - alphabet + r) % strlen(alphabet)] : t[i];
    }
    result[i] = '\0';
    printf("%s\n", result);
    free(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-15
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多