Search code examples
crealloc

Signal: SIGABRT (Aborted) @ realloc


i'm trying to add an extension to a c-string, but i just get Signal: SIGABRT (Aborted), can anyone tell me what's the reason for this? This is what i've done so far, the error comes @ realloc in function "prepareFileName":

#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;
}

Solution

  • file_name is in the text segment (read only) of your program. Use malloc() + strcpy() to allocate the space on the heap.

    See man realloc

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