首页 > 解决方案 > C 输出中的随机字节

问题描述

我刚刚用 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% 的时间里,并且在较长的字符串中发生得更频繁。请帮助解释并消除这一点。任何其他可以改进我的代码的技巧也值得赞赏。谢谢十几个!

标签: cpointersargvstdiostrchr

解决方案


字符串的结尾由字符 '\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);

推荐阅读