To make my code more readable, I tested to export the dynamic memory reservation (HEAP) in an extra function. Getting back a pointer to the startposition of the reserved memory.
But... how I can free the reserved memory after usage?
int i;
#define buffersize 5
// -------------------------------------------------------------------------------
char * dynReservation_of_Memory(long sizeOfBuf_in_Bytes) {
// -------------------------------------------------------------------------------
char *Buf = new(std::nothrow) char[sizeOfBuf_in_Bytes];
if (!Buf) { Serial.println("Error dyn. memory allocation >> Programmstopp"); while(1){}; }
//
for (byte i = 0; i<sizeOfBuf_in_Bytes; i++) {Buf[i] = i+20;} // test: filling the buffer with 20...24
//
return(&Buf[0]); // adress of first byte in buffer
} // ende Fkt
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("Test-Sketch");
//
char * Buffer = dynReservation_of_Memory(buffersize);
for (byte i = 0; i<buffersize; i++)
{ Serial.println(Buffer[i], DEC); } // does the buffer contains the testdata 20...24?
Serial.println("");
//
for (byte i = 0; i<buffersize; i++) // fill the buffer with new testdata 10...14
{ Buffer[i] = i+10; }
//
for (byte i = 0; i<buffersize; i++) // does the buffer contains the new testdata 10...14?
{ Serial.println(Buffer[i], DEC); }
Serial.println("");
// -----------------------------------------------------
delete[] Buffer; // free reserved memory
if (!Buffer) { Serial.println("Memory no more reserved..."); } // check, whether memory is free
else { Serial.println("why the <delete[] Buffer> doesn´t worked?");}
// -----------------------------------------------------
} // end of setup()
void loop() {
// -------------------------
Serial.print(i); i++; delay(5000);
} // end of loop
The response of my testprogram is:
*
Test-Sketch
20
21
22
23
24
10
11
12
13
14
why the <delete[] Buffer> doesn´t worked?
*