0

I'm having trouble with this Array 'Vector'.

It's not being returned from that function 'generateVector' with the same values it has inside. I presume the returning statement is provoking some kind of memory error. But I dont know what neither how to solve this.

    #include<stdio.h>
#include<time.h>
#include"meft_ist.h"


#define LOGMESSAGE "Error. Try again: "


enum { EXIT, GENERATE, SHOW, SAVE };


double *generateVector( int size, int max ) {

    usint i;

    // vector[0] transports array size
    double vector[size + 1];
    vector[0] = size;


    for(i = 1; i < size; i++)
        vector[i] = ( (double)rand() * max / (double)RAND_MAX ) + drand48();

/*  for(i = 1; i < (int)vector[0]; i++) -> here the vector is OKAY
        fprintf(stdout, "\n[%d] %.3lf", i, vector[i]);*/

    line(1, 1);
    fprintf(stdout, "** SUCCESS **");

    return vector;
}

void save(void) {

    FILE *f_data = fopen("savedata.txt", "rt");

    if
    fclose(f_data);

}

void showVector(double vector[]) {

    usint i;

    // -> here the vector IS CHANGED
    line(2, 0);
    for(i = 1; i < (int)vector[0]; i++)
        fprintf(stdout, "[%2.d] %.3lf%c", i, vector[i], (i % 5 == 0) ? '\n' : '\t');

    line(2, 0);
}

int exitProg() {

    fprintf(stdout, "[EXIT] Confirm? [y/n]");

    switch(getchar()) {
        case 's': case 'S':
        case 'y': case 'Y':

            line(2, 1);
            fprintf(stdout, "** THANKS **");
            line(1, 0);

            return false;
        default:
            return true;
    }
}

int interface() {

    double *vector;

    //clear();

    menu(4, "Generate", "Show", "Regist", "Exit");
    line(1, 1);

    sint option = (sint) i_dialog("Choice: ", LOGMESSAGE);

    switch(option) {
        case GENERATE:
            vector = generateVector(abs(i_dialog("Size: ", LOGMESSAGE)),
                                    i_dialog("Max: ", LOGMESSAGE));

        case SHOW:
            showVector(vector);

            break;

        case SAVE:
            save();
            break;

        case EXIT:
            return exitProg();

        default:
            return false;
    }
}

int main() {

    srand( (unsigned)time(NULL) );

    while(interface());

    return 0;
}
user3050910
  • 3,107
  • 3
  • 13
  • 11
  • 1
    Turn on your compiler warnings. It should warn you about this, as well as not returning a value from all paths of `interface()` – clcto Oct 20 '14 at 21:35
  • 1
    `double vector[size + 1];` replace with `double *vector = malloc((size+1)*sizeof(*vector));` – BLUEPIXY Oct 20 '14 at 21:37

1 Answers1

4

You are returning a pointer to an automatic variable. The variable goes out of scope the moment the function returns, leaving a dangling pointer. Doing anything with that pointer results in undefined behaviour.

The function either needs to take a pointer to a (pre-allocated) array, or allocate a new array on the heap and return that.

NPE
  • 486,780
  • 108
  • 951
  • 1,012