October 22, 2024
Chicago 12, Melborne City, USA
C++

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



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video