0

I'm declaring a pointer in main. I then allocating memory and initialize values inside a function, then return to main and print the data. For some reason when I allocate, initialize, and print in func1 it works. Once and I leave the func though I seg fault. I've googled this problem and search for about 2 hours on this site. I'm stuck.

Here is my code:

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

int func1(int *array);

int main() {

    int *array;
    func1(array);
    printf("Main: %d\n", array[1]);
    return 0;

}

int func1(int *array) {

    array = malloc(10 * sizeof(int));
    printf("Enter an int: ");
    scanf("%d", &array[1]);
    printf("Func1: %d\n", array[1]);
}

This is what my command line looks like:

Enter an int: 5
Func1: 5
Segmentation fault (core dumped)

1 Answers1

4

First a word about terminology, your variable array is technically not an array, it's a pointer. It can be made to point to memory that can be used as an array though.

Now for your problem: It's that when you pass arguments to functions those are passed by value, meaning they are copied. So in the function func1 the argument array is just a copy, and changing a copy will not change the original. Since the original is not changed, you will then in the main function dereference an uninitialized pointer, leading to undefined behavior and the crash.

To solve this you have to emulate pass by reference. This is done by passing the argument using a pointer. In this case you have to pass a pointer to the pointer.

First you of course need to change the function:

void func1(int **array) {

    *array = malloc(10 * sizeof(int));
    printf("Enter an int: ");
    scanf("%d", &(*array)[1]);
    printf("Func1: %d\n", (*array)[1]);
}

Then you need to use the address-of operator & when calling the function

int *array;
func1(&array);

An important note: The malloc function does not initialize the memory it allocates, which means that the contents of the memory is indeterminate. Only the second int element of the allocated memory is initialized and can be properly referenced, reading all other elements will also lead to undefined behavior.


Another thing, that also leads to undefined behavior, and as noted by Namfuak, is that in your original function func1 you declared it as returning an integer, but you don't actually return anything. That's why I changed the function here in my answer to return void.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621