0

In my attempt to learn a bit about pointers, I tried to create a program that allocates memory for an array of given size (where the size is defined by the value of the constant ARR_SIZE) and prints out elements of that array to the console.

I cannot understand the results I am getting... For example, when I run the code shown below, I get {0, 4206628, 4206628, 3, 4, 5, 6, 2686696, 8, 9}, which makes absolutely no sense to me. I would like to know what is the reason of such behaviour and what to modify in order to obtain the anticipated results.

#define ARR_SIZE 10

void print_array(int loc);
int memory_alloc();

int main()
{
    int array_loc = memory_alloc();

    print_array(array_loc);

    return 0;
}

void print_array(int loc)
{
    int i = 0;
    int *arr_ptr;

    arr_ptr = loc;

    while(i < ARR_SIZE)
    {
        printf("%d\n", *arr_ptr);
        *(arr_ptr++);
        i++;
    }
}

int memory_alloc()
{
    int array[ARR_SIZE];
    int i = 0;

    for(i; i < ARR_SIZE; i++)
    {
        array[i] = i;
    }

    return &array;
}
1
  • Have you looked at your compiler output? If it is half-decent, it should tell you what is wrong. Commented Sep 11, 2014 at 10:28

3 Answers 3

2

What you are observing is Undefined Behavior, because the array that was created in memory_alloc only exists in this function's scope. Once the program leaves it, that array will no longer exist.

An alternative is to allocate the array in the heap:

int memory_alloc()
{
    int *array = malloc(ARR_SIZE * sizeof(int));
    int i = 0;

    for(i; i < ARR_SIZE; i++)
    {
        array[i] = i;
    }

    return array;
}

After you're done using the array, it should be freed.

int main()
{
    int* array_pointer = memory_alloc();

    // use array here

    free(array_pointer);
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

1
int array[ARR_SIZE];

here integer array is local to function and it will not longer available after function end.

To make it work you can do like

static int array[ARR_SIZE];

And

return array; //no need &

Comments

1

the array that you are declaring in memory_alloc() function

int array[ARR_SIZE];

this array is a local variable. its scope is within the function memory_alloc() and as soon as this function returns, all the local variables are destroyed (so is your array[])

instead, declare the array in main(), and pass the array to memory_alloc().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.