0

I'm trying to create a two dimensional array but when i use free at the end of my program i always get "Segmentation fault (core dumped)" error. The sleep function is only used because i wanted to see if it crashes after creating the array or later, and the program crashes as soon as i use free(array)

#include  <stdio.h>
#include  <stdlib.h>
#include  <unistd.h>


void check(int number)
{
    if(number < 0)
    {
        fprintf(stderr, "You cannot use a value below zero!\n");
    }
}


int create_array(int **array, int size)
{
    array = (int**)malloc(size * sizeof(int*));

    for(int i = 0; i < size; i++)
    {
        array[i] = (int*)malloc(size * sizeof(int));
    }

    printf("Successfully created the array!\n");
    printf("The size of the array is %d * %d = %d", size, size, sizeof(array) / sizeof(int));

    return EXIT_SUCCESS;
}


int main(void)
{
    int N;
    printf("Please enter a value for N: ");
    scanf("%d", & N);
    check(N);

    int R;
    printf("Please enter a value for R: ");
    scanf("%d", & R);
    check(R);

    int **array;
    create_array(array, N);
    sleep(1);
    free(array);

    return EXIT_SUCCESS;
}
1
  • A better way of determining where it was crashing would be to step teh code in a debugger. You can also use a debugger to see that the pointer returned by malloc() is not the same value as that you pass to free(). Commented Jan 28, 2017 at 15:13

3 Answers 3

1

You are only modifying a local copy of array in create_array() function. In order to be able to modify the pointer array in main(), you need to pass a pointer to it (i.e. the function needs to receive a int***).

More simply, you can return the array from the function and assign it to the array in main() and you wouldn't need to pass the first argument.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much
1

you are creating dynamic array but you are not returning the reference of that array, thats why you are failing to free it.

Comments

0

You need to call create_array() as follows:

int **array;
create_array( &array, N);

Then define it as:

int create_array(int*** array, int size)
{
    *array = (int**)malloc(size * sizeof(int*));

    for(int i = 0; i < size; i++)
    {
        (*array)[i] = (int*)malloc(size * sizeof(int));
    }

    printf("Successfully created the array!\n");
    printf("The size of the array is %d * %d = %d", size, size, sizeof(array) / sizeof(int));

    return EXIT_SUCCESS;
}

You will still have a memory leak however since you are only freeing array and not freeing array[0] to array[N-1]. It would be safer to create a corresponding destroy_array() function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.