Hi all,
Anyone know why my function freeMsg() isn't actually working? If I put a line if(msg==NULL) it returns false, after the free(msg) command.
Cheers
template <typename mavlink_message_type>
class storage {
public:
storage(){
msg = static_cast<mavlink_message_type*>(malloc(sizeof(mavlink_message_type)));
}
mavlink_message_type* msg;
bool newData(){
if(this->msg == NULL){
this->msg = static_cast<mavlink_message_type*>(malloc (sizeof(mavlink_message_type)));
}
return true;
}
void freeMsg(){
if(msg != NULL){
free(msg);
}
}
};
system
January 12, 2012, 2:57pm
2
char* ptr;
free(ptr) can only free the memory pointed by ptr, but cannot modify ptr in any way. If it could do that, the signature would be free(char**), and you'd passit &ptr, not ptr.
Ok, that's confused me a little.
ptr is pointing to mavlink_message_type*, which I should explain is an instance of a structure.
by calling free(ptr), I effectively want to just delete the existence of that structure.
I have tried free(&msg), and that didnt work.
I have tidied the code up a bit:
void loop(){
Serial.print("Loop ");
Serial.print(counter++);
Serial.println(1+counter);
createMe();
freeMe();
}
bool createMe(){
Serial.println("Allocating memory");
msg = (mavlink_message_type*)(malloc(sizeof(mavlink_message_type)));
if (msg != NULL){
return true;
}
else{
Serial.println("Error in creating msg");
return false;
}
}
bool freeMe(){
Serial.println("Freeing memory");
free(&msg);
if (msg == NULL){
return true;
}
else{
Serial.println("Error in freeing msg");
return false;
}
}
The output I get is the following:
Allocating memory
Loop 0
1
Loop 1
2
Freeing memory
Error in freeing msg
Loop 2
101
Loop 3
4
Frng memory
Error in freeing msg
Loop 4
4
Loop 5
6
system
January 12, 2012, 3:07pm
4
After you free the memory pointed to, YOU must set the pointer to NULL. That is not done for you.
free(ptr);
ptr = NULL;
Gotcha,
Cheers Paul, didn't know that!
Si