Variables bursting

Asked

Viewed 63 times

1

The variables cont_setosa, cont_versicolor, cont_virginica are breaking at the end of the code, why?? How to fix this??

Before Ifs the variables are normal, but after them, there is this change...


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

typedef struct element{
    int index;
    long double dist;
}Element;

int main(int argc, char const *argv[])
{
    char *classe_aux, classe_main;
    classe_aux = &classe_main;

    int k = 3;
    int i = 0;
    Element el[3] = {{1},
                     {1},
                     {1}};

    int cont_setosa = 0;
    int cont_versicolor = 0;
    int cont_virginica = 0;

    for (i = 0; i < k; i++)
    {
        if (el[i].index == 0)
        {
            cont_setosa++;
        }
        else
        {
            if (el[i].index == 1)
            {
                cont_versicolor++;
            }
            else
            {
                if ( el[i].index == 2)
                {
                    cont_virginica++;
                }
            }
        }
    }

    printf("%i %i %i\n", cont_setosa, cont_versicolor, cont_virginica);

    if ( cont_setosa > cont_versicolor && cont_setosa > cont_virginica)
    {
        strcpy(classe_aux, "Iris-setosa");
    }
    else
    {
        if ( cont_versicolor > cont_setosa && cont_versicolor > cont_virginica)
        {
            strcpy(classe_aux, "Iris-versicolor");
        }
        if ( cont_virginica > cont_setosa && cont_virginica > cont_versicolor)
        {
            strcpy(classe_aux,"Iris-virginica");
        }
    } 

    printf("%i %i %i\n", cont_setosa, cont_versicolor, cont_virginica);
    return 0;
}

Exit:

0 3 0
1936876918 1819239273 29295
  • I could not reproduce this situation with your example code, need to make some modification?

  • No, it’s just run normally, there’s no code input, I tested it on two compilers on the computer and one online and it always keeps popping the variables...

1 answer

2


It seems to me that you are corrupting the stack/stack memory.

The variable classe_aux is a pointer that points to classe_main.

classe_main in turn is a variable of type char, it stores only one character, so when you do strcpy(classe_aux, "Iris-setosa") for example, you are allocating the first character 'I' in the classe_main, and the other characters are then allocated in the stack region at positions that other variables are using, corrupting your memory.

If you declare the variable classe_aux as an array of size 16 for example, this would already solve the memory problem in this case.

Link with the code working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.