I'm trying to use Google's protobuf. I use a subMessage, I set it with random values and store the subMessage in the mainMessage. Here are example messages that fit my case :
message subMessage{
required int32 val1= 1;
required int32 val2= 2;
required int32 val3= 3;
required int32 val4= 4;
}
message mainMessage{
required subMessage sub = 1;
}
My main :
int main (int argc,char** argv){
subMessage sM;
mainMessage mM;
sM.set_val1(10);
sM.set_val2(9);
sM.set_val3(8);
sM.set_val4(7);
I then tried :
mM.set_allocated_submessage(&sM);
but it result in a segmentation fault at the end of the program (Destruction of the object ?). The only way to solve it is to manually call mM.release_submessage();
.
I also tried :
*mM.mutable_submessage()=subMessage;
I don't get why I have a segmentation fault as my program stops right after (Nothing accessing/writing on my subMessage or my mainMessage).
According to Google's documentation :
void set_allocated_foo(Bar* bar): Sets the Bar object to the field and frees the previous field value if it exists. If the Bar pointer is not NULL, the message takes ownership of the allocated Bar object and has_foo() will return true. Otherwise, if the Bar is NULL, the behavior is the same as calling clear_foo()
It seems that mainMessage has the ownership after set_allocated_foo()
, but it results in a Segmentation fault. In the other hand, the mutable_foo()
seems to duplicate the data. I would like to avoid duplicating datas as I'm going to run on Raspberry with low RAM, but the set_allocated_foo()
is too mysterious for me for the moment. I don't get the difference between theses two...
Do you think I should use .set_allocated_foo()
and manually release it, or use .mutable_foo()
?
Thanks.
PS : I'm aware of this topic about set_allocated_foo() but my problem isn't about deleting or not but more about rights on the pointers/datas and didn't help me solving my problem