C程序中的分段错误(核心转储)

时间:2015-02-20 22:35:16

标签: c segmentation-fault initialization warnings

我有以下程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 255

char * decrypt(char *p, int key){
    char *tmp;
    for(int i = 0; p[i] != '\0'; i++){
        tmp[i] = p[i]-key;
    }
    return tmp;
}

int main(void){
    printf("Hallo Welt!");
    printf("%s\n", decrypt("ibmmp", 1));
    return EXIT_SUCCESS;
}

当我用gcc -Wall编译它时,我运行时会收到警告tmp could get uninitialized in this function [-Wmaybe-uninitialized] tmp[i] = p[i]-key(翻译自德语)和分段错误(核心转储)./crypto

导致该错误的原因是什么?

我知道这个问题已被多次询问,但我无法修复此警告,因为其他人有不同的源代码,我无法适应我的问题。

2 个答案:

答案 0 :(得分:1)

你需要分配'tmp',然后保持良好的'c'编码,检查分配是否成功。我假设你已经定义了MAX,所以你可以设置字符串长度的上限,所以我在下面使用它。如果MAX是而不是为空的字符数,则需要'malloc(MAX +1)'。如果要包含NULL,则只需保留下面定义的代码即可。你还想决定在malloc失败时返回什么。我返回NULL,但您可能希望根据您的需要做一些不同的事情。

另外请注意,此函数正在返回已分配的内存,因此有人需要释放它以便您不会泄漏内存。

char * decrypt(char *p, int key){
    char *tmp;
    tmp = (char *) malloc(MAX);
    if(!tmp)
        return NULL;
    for(int i = 0; p[i] != '\0'; i++){
        tmp[i] = p[i]-key;
    }
    return tmp;
} 

答案 1 :(得分:0)

在使用前为tmp分配内存。确保在返回字符串之前将其终止。

// Make the input a const string.
// char * decrypt(char *p, int key){
char * decrypt(char const* p, int key){
    char *tmp = malloc(strlen(p) + 1); // Allocate memory
    int i = 0;
    for( ; p[i] != '\0'; i++){
        tmp[i] = p[i]-key;
    }
    tmp[i] = '\0';                     // null terminate.
    return tmp;
}

确保取消分配内存。只是使用

printf("%s\n", decrypt("ibmmp", 1));

会导致内存泄漏。

int main(void){
    printf("Hallo Welt!");
    char* dec = decrypt("ibmmp", 1)
    printf("%s\n", dec);
    free(dec);                        // Deallocate memory.
    return EXIT_SUCCESS;
}