coverflow

Stack smashing detected error in recursive function


I am trying to write a program that gets input step and prints the following in LATEX format:

enter image description here

The output is 1+\frac{2+\frac{4}{5}}{3+\frac{6}{7}}

This is the code I have written, but I get a *** stack smashing detected ***: terminated error for inputs more than 6.

Any idea how to manage this (at least for inputs lower than 10)?

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

void frac(int start, int step, char *result) {
    if (step == 1) {
        sprintf(result, "%d", start);
    } else {
        char left[256];
        char right[256];
        frac(2 * start, step - 1, left);
        frac(2 * start + 1, step - 1, right);
        sprintf(result, "%d+\\frac{%s}{%s}", start, left, right);
    }
}

int main() {
    int step;
    scanf("%d", &step);
    
    char result[1024];
    int start = 1;
    frac(start, step, result);
    printf("%s\n", result);
    
    return 0;
}

Solution

  • You get stack smashing message because you cause buffer overflows in your function.

    For steps 2-6 your resulting lengths are 13, 37, 91, 203, 427. That means, with any additional step, the length more than doubles.

    Step 7 will already exceed your buffer length. Maybe not in the result buffer but clearly in your left and right buffers which should be around half of the result size.

    You need to provide larger buffers for your strings.

    As your buffers are located on the stack which has limited size, you might also change to dynamically allocating your buffers.