首页 > 解决方案 > ROT13 实现中的分段错误和警告

问题描述

我正在编写一个实现 rot13 的函数,我只制作 a,b,...,m (+13) 的情况,但我有一个分段错误错误和警告:

代码:

#include <stdio.h>
#include <string.h>
char rot13(char palabra[]) { //char *palabra
    int y = (short) strlen(palabra);
    char abc[27]="abcdefghijklmnopqrstuvwxyz";
    for (int i = 0; i < y ; ++i) {
        if(palabra[i]<'m' && palabra[i]>='a'){
            for (int j = 0; j <26 ; ++j) {
                if (palabra[i]==abc[j]){
                    palabra[i]=abc[j+13];
                }
            }    
        }    
    }

    return palabra;
}

int main() {
    rot13("aaa");
    return 0;
}

警告:

main.c:18:12: warning: return makes integer from pointer without a cast [-Wint-conversion]
     return palabra;

我需要帮助来理解警告以及如何解决问题,谢谢!

标签: csegmentation-fault

解决方案


Another major problem is that your code is trying to change a string literal (the "aaa") which is considered undefined behavior in C. Compilers are free to store string literals in a read-only memory region.

It's doing it in palabra[i]=abc[j+13];, where you overwrite each byte of the input parameter.


推荐阅读