信号:SIGABRT(中止)@ realloc

信号:SIGABRT(中止)@ realloc

问题描述:

我想添加一个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

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

man realloc

除非PTR是NULL,它必须是由先前调用返回 的malloc(),释放calloc()或realloc()。

+1

谢谢你的答案(我必须等待8分钟,直到我可以接受它) – Pedro

+0

没问题。你也可以考虑使用'asprintf(...,“%s。%s”,file_name,扩展名)'' – Kevin