0

I have the beginnings of a C program to simulate Cache, but I am running into a confusing problem. First I have a function to generate the cache:

int * generateCache(int cacheSize){
  int cache[cacheSize];

  for(int cacheIndex = 0; cacheIndex < cacheSize-1; cacheIndex++){
    cache[cacheIndex] = -1;
  }
  return cache;
}

And in my main function is this:

int main(){
  int cacheSize = 16;
  int * cache = generateCache(cacheSize);
  for(int i = 0; i < cacheSize; i++){
    printf("%d %d\n", i, cache[i]);
  }

  return 0;
}

But my output is this:

warning: address of stack memory associated with local variable 'cache' returned [-Wreturn-stack-address]
return cache;
1 warning generated.
0 -1
1 -1
2 -1
3 -1
4 -1
5 -1
6 -1
7 -1
8 -1
9 -1
10 -1
11 -1
12 0
13 0
14 0
15 0

Can anyone tell me why the last 4 indexes are initialized to 0? This happens regardless of what I initialize the first 12 indexes to; the last 4 are always 0. Thank you.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
hobbsdevon
  • 23
  • 4
  • 3
    You are returning the address of *local* array. Which is ceasing to exist once the function is done. – Eugene Sh. May 10 '21 at 19:42
  • 2
    The warning is surprisingly descriptive by the way. – Eugene Sh. May 10 '21 at 19:46
  • Right, I thought I could pretty much ignore the warning. How might I go about fixing it? And why are the first 12 values as they should be? I don't quite understand what you mean by returning the address of a local array. I thought returning the address is a sort of way around the fact that it's a local array. I should be able to access that array in main because it's an address, right? – hobbsdevon May 10 '21 at 19:56
  • 1
    Perhaps the cache should be one or more of: global in scope, static, or not created in the function and passed into the function. – mrflash818 May 10 '21 at 19:59
  • Okay. The size of the cache array must be variable, which I believe rules out all three of these if I'm not mistaken. The program should be able to take user input for the cache size. If it simply cannot be variable I can initialize it as the max cache size, but I'd like to avoid this if possible. – hobbsdevon May 10 '21 at 20:05

1 Answers1

3

Instead of a local variable:

int cache[cacheSize];

use a heap-allocated variable:

int * cache = malloc(sizeof(int) * cacheSize);

Also make sure to check if the allocation was successful. See malloc(3):

On error, these functions return NULL.

And to later call free(cache).

mkayaalp
  • 2,631
  • 10
  • 17