1

I have a function which I give a char** input. Inside the function I am calling realloc. I am calling the function multiple times without any issues, but it always crashes at the same point with

"Exception has occurred. - Unknown signal".

The function is implemented as follows:

int look_and_say(char** input, char** output) {
    if (input == NULL) {
        return -1; // Handle null input
    }
    
    size_t len = strlen(*input);
    
    if (len == 0) {
        return -1; // Return -1 as sign for empty input string
        printf("Input string empty\n");
    }

    if( len *2 +1 > MAX_INPUT_SIZE){
        return -5; // Handle input too large
        printf("Input too large\n");
    }

    printf("Size to allocate: %zu __ ", len * 2 + 1);

    char* temp_storage = NULL;
    temp_storage = (char*)realloc(*output, len * 2 + 1); //always crashes here when allocating 6365 bytes

    if (temp_storage == NULL) {
        return -2; // Handle memory allocation failure
    }
    *output = temp_storage;

    int count = 1;
    int current = *input[0];
    int new_len = 0;

    for(int i = 1; i <= len; i++){
        if((*input)[i] == (*input)[i-1]){
            count++;
        } else {
            new_len += sprintf(*output + new_len, "%d%c", count, (*input)[i-1]);
            count = 1; // Reset count for the new character
            current = (*input)[i];
        }
    }
    // append terminating character
    (*output)[new_len++] = '\0';
    return 1; // Return 1 as sign for successful processing
}

I tried it first with allocating directly enough for the end result without reallocating, which works, but I am not satisfied with that solution. I also tried compiling with -Wall and -Wextra without success

Edit 1:

  • I have removed the unused variable current
  • I have removed the typecast For some reason the code crashes a bit later now.

I addition here is my main():


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


#define MAX_INPUT_SIZE 20000000 //20'000'000
int main(){

    // ######################################Task 1######################################
    char *input = malloc(12 * sizeof(char)); // Allocate memory for input
    if (input == NULL) {    
        printf("Memory allocation failed\n");
        return 1;
    }
    strcpy(input, "1321131112");

    char* result = NULL; // Initialize result to NULL


    for(int i = 0; i < 25; i++){
        printf("Input length: %zu __ ", strlen(input));
        int status = look_and_say(&input, &result);
        printf("Output length: %zu \n", strlen(result));
        if (status < 0) {
            printf("Error processing input: num: %d status:%d\n", i, status);
            return 1;
        }
        

        strcpy(input, result); // Update input for the next iteration
        //free(result); // Free the previous result to avoid memory leaks
    }
    //printf("Result: %s\n", result);
    printf("Final result length: %zu\n", strlen(result));
    free(result); // Free the allocated memory for the result
    free(input); // Free the allocated memory for the input
    
    return 0;
}

Edit 2:

  • added #include and #define
  • regarding for loop: I am using i <= len to compare to the final null character on purpose, as in this iteration I then add the final required numbers
17
  • 3
    one probable possibility is *output does not contains an already allocated buffer when you call realloc (the null pointer is the alone other valid case). Use valgrind to check your memory management (and more) Commented Jun 22 at 19:32
  • 4
    But what would really help us to help you, is to see a proper minimal reproducible example. I would say the most important bit, the very first call to this function, is very crucial. Together with what happens if count becomes a double-digit number. Commented Jun 22 at 19:48
  • 2
    Address sanitizer says that your program overflows heap buffer in strcpy(input, result); // Update input for the next iteration Commented Jun 22 at 20:37
  • 2
    Definitely related and on topic: In the function you allocate strlen(input) * 2 + 1 characters for the result. Then copy this possible very much longer string into the 12 bytes allocated for input. What happens if strlen(result) is equal to or larger than 12 bytes? Commented Jun 22 at 20:58
  • 2
    So the error was not in the code you given us, and then no change for us to find it. This is why it is required to give a minimal reproducible example and not a part of it. Considering your error I don't think it will be useful for other people. DId you use valgrind ? if not I encourage you to try your old version with it, that tools is really useful, even when you think a program is correct I recommended to verify using it Commented Jun 24 at 15:20

1 Answer 1

1

The problem laid in the main() code, which I did not include in the post until my first edit. This was my first error.
I was assigning the result to a char array / pointer, without increasing its allocated memory. Due to this at one point the memory was too small and the program crashed.

The exact solution:

In the main() the strcpy(input, result); is writing on input without reallocating a larger memory block.

I added

*input = realloc(*input, new_len); // Resize input to fit the new result
    if (input == NULL) {
        return -3; // Handle memory reallocation failure
    }

at the end of look_and_say and this resolved the issue.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.