I've been teaching myself about pointers, struct, and Malloc. I have an example sketch that highlights a mystery. In my example, I have a simple struct with a String, bool, and int. I set values in a struct that is simply created as a global. Using the 'name.variable' syntax all works as expected, simple. I also created a pointer to a struct and the 'pointer->variable' syntax works as expected for String, bool, and int. Again, all good. Lastly, I used Malloc to get a chunk of memory using the same struct of String, bool, and int. I can successfully assign and retrieve bool, and int. My problem is I can assign a String but cannot retrieve it as a legible String. I know that Malloc is not a good practice with microprocessors. I came across this just as an experiment. I've been testing this with an ESP32 on the 2.0 RC3 IDE.
Here is my example sketch.
struct test1 {
bool found{true};
int value1{10};
String name = "Howdy Doody";
} foo, bar, *barPtr, *cat;
void setup() {
Serial.begin(115200);
cat = (struct test1*)malloc(sizeof(struct test1) );
Serial.print("cat address-->");
Serial.println((int)cat/4); // Malloc seems to give a working address
cat->name = "dog"; // cat->name is assigned 'dog' (or so I thought)
Serial.print("cat->name address -->");
Serial.println((int)&cat->name/4); //Address of cat->name
//
if (cat->name == "dog") Serial.println("cat->name is equal to dog"); //This test should be true, just assigned above
cat->found = false; //This assignment works as expected
cat->value1 = 5; //This assignment works as expected
foo.name = "Maxwell"; //This assignment works as expected
//
barPtr = &bar; //Test of struct pointer without Malloc involved
barPtr->name = "Winnie";
//
Serial.print("cat->name -->");
// This is the offending statement
Serial.println(cat->name); //Why doesn't this print 'dog' ?
//
Serial.print("cat->name address -->");
Serial.println((int)&cat->name/4); //making sure still pointed at where 'dog' was stored
Serial.print("cat.value -->");
Serial.println( cat->value1); // int values prints correctly
Serial.print("cat->found -->");
Serial.println( cat->found); // boolean value prints correctly
// values from a global struct 'test1' work correctly
Serial.print("foo.name -->");
Serial.println( foo.name); // This correctly prints 'Maxwell'
Serial.print("foo.found -->");
Serial.println( foo.found);
Serial.print("foo.value1 -->");
Serial.println( foo.value1);
// test of pointer to struct bar - no malloc involved
Serial.print("bar->name -->");
Serial.println( barPtr->name); // Other pointer to struct name works as expected
Serial.print("barPtr->value1 -->");
Serial.println( barPtr->value1);
free(cat);
}
void loop() {
// put your main code here, to run repeatedly:
}
I hope this is readable. I've tried to eliminate any other issue other than Malloc with a String in a struct. I've been at this for three hours and it remains a mystery why the struct using Malloc will seemingly not work. Any thoughts from minds greater than mine?