codeplea/tinyexpr

Cannot use with trim function

amiralisalimi opened this issue · 1 comments

I am trying to use tinyexpr in my project. Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lib/tinyexpr.h"

#define TRUE 1

void cexpGen();
char *trim(char input[]);

int main()
{
    cexpGen();
    getchar();
    return 0;
}

void cexpGen()
{
    char c_exp[18] = "1 2 3 4 5 6 7 8 9";
    char expressions[4] = "+- ";

    int index[8];
    char c[9];

    int j = 1;

    for (int i = 0; i < 8; i++)
    {
        c[i] = '+';
        index[i] = 0;
    }

    while (TRUE)
    {
        if (te_interp(trim(c_exp), 0) == 100)
        {
            printf("%s = 100", c_exp);
        }

        int k = sizeof(index) / sizeof(index[0]) - 1;
        for (; k >= 0; k--)
        {
            index[k] += 1;
            if (index[k] < 3)
            {
                c[k] = expressions[index[k]];
                break;
            }

            index[k] = 0;
            c[k] = expressions[index[k]];
        }

        for (int i = 0; i < 8; i++)
        {
            if (j >= 17)
                break;

            c_exp[j] = c[i];

            j += 2;
        }

        j = 1;

        if (k < 0)
            break;
    }
}

char *trim(char input[])
{
    char output[18];
    for (int i = 0; i < (strlen(input) - 1); i++)
    {
        output[i] = input[i];
    }

    for (int i = 0; i < 18; i++)
    {
        if (isspace(output[i]))
        {
            for (int j = i; j < strlen(output); j++)
            {
                if (j == (strlen(output) - 1))
                {
                    memmove(&output[strlen(output) - 1], &output[strlen(output)], strlen(output) - (strlen(output) - 1));
                }

                output[j] = output[j + 1];
            }
        }
    }

    return output;
}

On line 36 (cexpGen(), while (TRUE), First if statement) when I want to interpret my code with te_interp(), It gives me segmentation fault when I use my trim() function, But it disappears when I remove trim(). What have I done wrong? (memmove(&output[strlen(output) - 1], &output[strlen(output)], strlen(output) - (strlen(output) - 1)); removes wanted characters of an array by changing them to '\0').

Sorry for this mistake, trim() just returns a string.