0

I need to find max size of array that my computer can create. I use below code for find that in C. But it gives me 300 as an input. But i can allocate more than 1 million. I need to find exact value about that. My Code:

int main(){
 int *dizi=(int *)malloc(sizeof(int));
 int i=1,x=1,sayac;
 while(x!=0){
      dizi=(int *)realloc(dizi,i*sizeof(int));
      sayac++;
      if(dizi[sayac]==NULL){
           x=0;
      }
 }
 printf("%d",sayac);
 free(dizi);

}

selbie
  • 100,020
  • 15
  • 103
  • 173
Erkan
  • 21
  • 7
  • Check `dizi == NULL` rather than `dizi[sayac] == NULL`. If your memory reallocation fails, it is `dizi` that will be NULL. Try using a loop with counter `i` and increasing it by a large amount each time round the loop, – John D Oct 29 '16 at 08:37
  • I did that. İt is still counting. I think it will work perfectly. I will let you know about the result. Thank you – Erkan Oct 29 '16 at 08:50
  • it did not worked bro. dizi is the first element of array so it cant be null. I changed realloc as malloc. it gave me 286k but it is not true data. – Erkan Oct 29 '16 at 08:59
  • It's true that an array can't be null - but `dizi` is a pointer to `int` which can be null. Your question has been marked as a duplicate so have a look at that. Good luck! – John D Oct 29 '16 at 09:32
  • I looked that topic but i could not find my answer bro. I mean how can i find the exact max value of size of an array that my computer can allocate with using malloc, calloc or realloc functions. For integer type. At that topic, there were not the finding a value. – Erkan Oct 29 '16 at 18:31
  • Those examples exit the loop when the pointer is zero. At that point, you know how much memory you tried to `realloc` and failed - it was `i*sizeof(int)` - so `(i-1)*sizeof(int)` is the maximum memory you can allocate. Note that this includes "virtual memory". – John D Oct 29 '16 at 18:56
  • If you use `malloc`, you need to `free` the memory you allocated on the previous loop - it won't be freed automatically. `realloc` does the `free` for you. If you don't free them, they continue to take up memory and affect the final count. The other question discusses more of the problems you will face as your memory requests get bigger and bigger. – John D Oct 29 '16 at 19:08

0 Answers0