Do while loop with array not working?

Newbie using an ESP32 trying to fill an Oled screen with pixels.
Somehow, the program seems to crash at the do…while loop. When disabled the screen gets filled with pixels.
I would like to make sure it is not placing a pixel twice.
Any help is appreciated.

void SendToScreen( int pos ){
  u8g2.setDrawColor( 1 );
  u8g2.drawPixel( pos % 128, pos / 128 );
  u8g2.sendBuffer();
}


void FillScreen(){


  int ScrBuffer[8192]= {};
  int x;


  for( int k= 0; k < 8192; k++ ){


    do{ 
      x= random(8192);
    } while( ScrBuffer[x] == 1 );
  
    ScrBuffer[x]= 1;   
    SendToScreen( x );
  }
}

It's not crushing it's looping forever here

do{ 
      x= random(8192);
    } while( ScrBuffer[x] == 1 );

What are you trying to achieve by this loop?

But why?

I initialised the array to 0 right? So at least the first time it should put a pixel on the screen?

I would like to keep a record of the pixels it has drawn on the screen and avoid a pixel being drawn twice.

I initialised the array to 0 right?

No. You initialised it to whatever was previously in the memory

Either make the array global or local and static and it will be initialised to zeroes. While you are at it make it an array of bytes not ints.

Ok, i Will make the changes you suggested. But i still don't understand why the do while loop doesn't work. If the values are previous memory values then it is hard to believe that they are all 1? Or is the condition in the loop wrong?

Make the changes and post your new code here and I will try it out

Ok, After some reading, and trying, i found out that when i created the array with more than about 6500 elements, the code wouldn’t work. I read that array’s are created on the stack memory And if you use malloc or calloc you are reserving memory on heap memory. So after some digging, the code below works. I do need to read more on stack and heap, but that’s what this is all about for me, learning something new.

void SendToScreen( int pos ){
  u8g2.setDrawColor( 1 );
  u8g2.drawPixel( pos % 128, pos / 128 );
  u8g2.sendBuffer();
}

void FillScreen(){

  byte * ScrBuffer;
  int ScrBufferSize= 8192;
  int x= 0;

  ScrBuffer = (byte*) calloc (ScrBufferSize,sizeof(byte));
  if (ScrBuffer == NULL) exit (EXIT_FAILURE);
  
  for( int k= 0; k < ScrBufferSize; k++ ){
    do{ 
      x= random(ScrBufferSize);
    } while( ScrBuffer[x] == 1 );
  
    ScrBuffer[x]= 1;   
    SendToScreen( x );
  }
  free(ScrBuffer);
}

And here I always thought the heap & stack were just different ends of the same pile of RAM.

-jim lee