[英]Segmentation fault (core dumped) in C program
我有以下程序:
#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
(德語翻譯)和分段錯誤(core dumped)。我運行加密貨幣
是什么導致該錯誤?
我知道這個問題已經被問過很多次了,但是我無法解決這個警告,因為其他人有不同的源代碼,並且我無法適應我的問題。
您需要分配“ tmp”,然后使用良好的“ c”編碼,檢查分配是否成功。 我假設您已定義MAX,因此可以在字符串的長度上設置上限,因此我在下面使用它。 如果將MAX設置為不帶null的字符數,則需要'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;
}
在使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.