0

I am trying to change the size of the array from another function. The code compiles but the program crashes... I am stuck, very stuck. New to this, my head is spinning up down left right aaaaah........

array.c

struct array {
    int* data;
    int size;
};

struct array* array_create()
{
    struct array* array = (struct array*) malloc(sizeof(struct array));
    array->data = (int*) malloc(sizeof(int) * 10000);
    array->size = 10000;
    return array;
}

void array_resize(struct array* array, int size)
{
    if (size > array->size) {
        free(array);
        array->data = (int*) malloc(sizeof(int) * size);
    }

    array->size = size;
}

int array_size(struct array* array)
{
    return array->size;
}

array.h

typedef struct array* ARRAY;

ARRAY array_create();
void array_resize(struct array* array, int size);

edit.c

void edit()
{
    array_resize(array, 100); // I can run the code but program crashes
}

main.c

ARRAY array;
array = array_create();
edit();                       // Program crashes
user3285214
  • 21
  • 1
  • 5

2 Answers2

1
    free(array);
    array->data = (int*) malloc(sizeof(int) * size);

Here you free array, and dereference it at the next line. That's undefined behavior. But seems to be the cause of your crash.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
1

This:

void array_resize(struct array* array, int size)
{
    if (size > array->size) {
        free(array);
        array->data = (int*) malloc(sizeof(int) * size);
    }

    array->size = size;
}

Should be free(array->data) not free(array). Or better realloc array->data.

Also, unless you are looking for trouble, declare your functions in your .h files as you do in your .c files, i.e.:

struct array;
struct array *array_create();

and include array.h from array.c.

abligh
  • 24,573
  • 4
  • 47
  • 84
  • Crashes where and how? Compile it with `-Wall` and fix all the warnings. Run it under `gdb` and see where it crashes. Run it under `valgrind`. If you are still stuck, post back the exact code you are running in a compilable state. – abligh Feb 09 '14 at 18:11