tiborb
tiborb

Reputation: 3

An array is preserving data between function calls in C

Why is the data preserved for the second call when I haven't used static?

Here is the code, the output and what I've expected the output should be.

#include <stdio.h>

void fun(int len)
{
  int arr[10];
  int i;

  for (i = 0; i < len; i++)
    arr[i] = (i+1) * 10;

  for (i = 0; i < 10; i++)
    printf("%d ", arr[i]);

  printf("\n");
}

int main(void) {
  fun(10);
  fun(4);

  return 0;
}

output:

10 20 30 40 50 60 70 80 90 100 
10 20 30 40 50 60 70 80 90 100

expected output:

10 20 30 40 50 60 70 80 90 100 
10 20 30 40 0 0 0 0 0 0 

Upvotes: 0

Views: 102

Answers (4)

Roger
Roger

Reputation: 1

array arr[] is allocated in stack which is uninitialized by default, the values are the ones used last time this area was allocated, in this it happens to allocate the same stack area between the 2 fun calls, and the stack area was initialized by the first call.

Upvotes: 0

ggorlen
ggorlen

Reputation: 56965

int arr[10]; declares an array of 10 int elements on the stack. Its elements are uninitialized. If you attempt to access them without initialization, as is the case with fun(4), you may see garbage values, you may happen to see old memory contents (as you did here), or you may crash the program with a segmentation fault if the memory page belongs to another program. You may even get your expected output! In fact, anything can happen because behavior is undefined by the specification.

To meet your expectations, initialize the array in any way you choose, such as one of the following:

int arr[10] = {};
int arr[10] = {0};
int arr[10];
memset(arr, 0, sizeof(int) * 10);
int arr[10];

for (int i = 0; i < 10; i++) {
    arr[i] = 0;
}

etc.

Upvotes: 3

Mad Physicist
Mad Physicist

Reputation: 114320

You are invoking undefined behavior by accessing uninitialized memory. The result could be literally anything, including your computer growing legs and running away.

In practice, what is probably happening is that your function calls occupy the same place on the stack since there are no other calls between or within them. The arr variable ends up on the same spot on the stack both times. The first initialization is more comprehensive than the second, so you don't see total garbage. This is to be expected, but certainly never relied upon.

Upvotes: 0

Julian
Julian

Reputation: 1612

Please initialize array.

Like this

void fun(int len)
{
  int arr[10] = {0};  //changed
  int i;

  for (i = 0; i < len; i++)
    arr[i] = (i+1) * 10;

  for (i = 0; i < 10; i++)
    printf("%d ", arr[i]);

  printf("\n");
}

Upvotes: 0

Related Questions