gpt4 book ai didi

c - 信号 : SIGABRT (Aborted) @ realloc

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:34 24 4
gpt4 key购买 nike

我正在尝试向 C 字符串添加扩展,但我只收到信号:SIGABRT(中止),谁能告诉我这是什么原因?这是我到目前为止所做的,错误出现在函数“prepareFileName”中的@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;
}

最佳答案

file_name 位于程序的文本段(只读)中。使用malloc() + strcpy() 分配堆上的空间。

参见man realloc

Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc().

关于c - 信号 : SIGABRT (Aborted) @ realloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47612898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com