2017-12-02 175 views
0

我想添加一個c字符串的擴展名,但我只是得到信號:SIGABRT(中止),誰能告訴我這是什麼原因?這是我到目前爲止已經完成,錯誤出現@ realloc的函數「prepareFileName」:信號:SIGABRT(中止)@ realloc

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


#define OUT_OF_MEMORY 3 
#define FILE_EXTENSION ".txt" 

typedef enum _Bool_ // enum _Bool_ is a non-typedef'ed enum 
{ 
    FALSE = 0, // Enum element 
    TRUE = 1 // Enum element 
} Bool; // Bool is the typedef'ed enum 

Bool cStringEndsWith(const char *sourceString, const char *suffix) { 
    if (!sourceString || !suffix) // Check for not null pointer 
    { 
    return FALSE; 
    } 
    size_t length_of_c_string = strlen(sourceString); 
    size_t length_of_suffix = strlen(suffix); 
    if (length_of_suffix > length_of_c_string) { 
    return FALSE; 
    } 
    int compare_result = strncmp(sourceString + length_of_c_string - length_of_suffix, suffix, length_of_suffix); 
    if (compare_result == 0) { 
    return TRUE; 
    } else { 
    return FALSE; 
    } 
} 

int prepareFileName(char **ptr_file_name){ 
    int ends_with_file_extension = cStringEndsWith(*ptr_file_name, FILE_EXTENSION); 
    if(!ends_with_file_extension) 
    { 
    char *new_ptr_file_name = realloc(*ptr_file_name, strlen(*ptr_file_name) + strlen(FILE_EXTENSION) + 1); 
    if(!new_ptr_file_name) 
     return OUT_OF_MEMORY; 
    *ptr_file_name = new_ptr_file_name; 
    strcat(*ptr_file_name, FILE_EXTENSION); 
    } 
} 

int main() 
{ 
    char *file_name = "testFileName"; 
    printf("Filename unprepared: \"%s\"", file_name); 
    prepareFileName(&file_name); 
    printf("Filename prepared: \"%s\"", file_name); 
    return 0; 
} 
+0

您是否試圖在'char * file_name'修改可能只讀的內存? –

+0

哦,謝謝你user3121023,我的壞,我不知道, – Pedro

回答

3

file_name是在文本段(只讀)你的程序的。使用malloc() + strcpy()來分配堆上的空間。

man realloc

除非PTR是NULL,它必須是由先前調用返回 的malloc(),釋放calloc()或realloc()。

+1

謝謝你的答案(我必須等待8分鐘,直到我可以接受它) – Pedro

+0

沒問題。你也可以考慮使用'asprintf(...,「%s。%s」,file_name,擴展名)'' – Kevin