Vladimir
Vladimir

Reputation: 292

Function always returns pointer to null

Why does createArray function returns pointer to 0? I guess, that i should use malloc to fix it, but why?

   int *createArray(int size)
{
    int i;
    int arr[size];

    i = 0;
    while (i < size)
    {
        arr[i] = i;
        i++;
    }
    return arr;
}

int main()
{
    int *ar;
    printf("%i", (createArray(10)));
}

Upvotes: 0

Views: 70

Answers (3)

Keith Thompson
Keith Thompson

Reputation: 263217

The basic problem is that your function is returning the address of a local variable. That local variable no longer exists once the function returns, so any pointer to it is invalid.

To correct some of the problems with your code, I added #include <stdio.h> to the top (required for printf) and changed your printf call from

printf("%i", (createArray(10)));

to

printf("%p\n", (void*)createArray(10));

When I compile with gcc and run the program, the output is:

(nil)

meaning that your function is returning a null pointer. (It's not a "pointer to null"; the pointer is null.) That's not what I would have expected; I expected a invalid garbage pointer value. (When I use tcc rather than gcc, I get 0x7fffd95a7140.)

Apparently gcc recognizes that your code has undefined behavior, and replaces the return statement with the equivalent of return NULL;. This is a perfectly legitimate transformation (and it might prevent your program from doing something nasty with the invalid pointer, modifying memory that your program doesn't own).

Bottom line: Your program has undefined behavior, and you can't assume anything about what it will do. And yes, allocating an array using malloc and returning the address of the allocated array is one way to fix it.

Upvotes: 1

dbush
dbush

Reputation: 223699

When you return an array from a function, you're actually returning a pointer to the first element of the array. And when a function returns, the memory used by its local variables are no longer valid.

So you're returning a pointer to a variable that no longer exists. Using that pointer in any way invokes undefined behavior. In this particular case, the invalid address is able to be dereferenced and happens to contain the value 0, however there's no guarantee that behavior will be consistent when you make changes to your program.

For this to work, you need to dynamically allocate memory. Then it can be used though the lifetime of the program.

int *arr = malloc(sizeof(*arr) * size);

This also means you'll need to free this memory when you're done using it:

int *ar = createArray(10);
printf("%i", ar[0]);
free(ar);

Upvotes: 1

Dario Airoldi
Dario Airoldi

Reputation: 46

arr variable is allocated on the stack. When returning from your function the stack is freed. The pointer you are returning will then point to an invalid memory location that may be set to null.

Upvotes: 1

Related Questions