6

I am new to using google protobuffers and I created a basic message:

message msg {  
    uint32 id = 1;                             
    google.protobuf.Timestamp timestamp = 2;  
}

Now I created a small c++ program to use this [with the necessary headers]

int main(void) {
  auto m = msg{};
  m.set_id(2);
  auto timestamp = google::protobuf::Timestamp{};
  timestamp.set_seconds(time(NULL));
  timestamp.set_nanos(0);

  m.set_allocated_timestamp(&timestamp);

  std::cout << m.id() << std::endl;
  std::cout << m.timestamp().seconds() << std::endl;

  return 0;
}

However, this program gives a seg fault.

free(): invalid pointer
[1]    9537 abort (core dumped) 

where do I need to release memory?

Mike
  • 3,775
  • 8
  • 39
  • 79
  • Offtopic: `timestamp.set_seconds(time(NULL));` is also undefined behavior. No risk of crash, just you do not have a warranty that `time` returns seconds. – Marek R Jul 15 '19 at 15:17
  • timestamp.set_seconds(time(NULL)); comes from the official protocol buffer site https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Timestamp but obviously I am open to better suggestions. – Mike Jul 15 '19 at 15:24
  • @MarekR for all intents and purposes, you do have this guarantee. – SergeyA Jul 15 '19 at 15:34

1 Answers1

5

A protobuf's set_allocated_foo() function will take ownership of the pointer and attempt to free it after message itself runs out of scope. See more at https://developers.google.com/protocol-buffers/docs/reference/cpp-generated

Since your pointer points to the automatic object, attempt at deleting this pointer yields undefined behavior, in your case, a coredump.

To set protobuf's TimeStamp, you first have to obtain a pointer to it using mutable_timestamp, and than you can set it's individual fields.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • Unfortunately, there is no set_timestamp. I used set_allocated_timestamp as I could not find another set method to my surprise. So my actual question here is more: How do I set timestamp in a message – Mike Jul 15 '19 at 15:25
  • Then you have to `new` it instead of using an automatic object. – Goswin von Brederlow Jul 15 '19 at 15:29
  • @Mike my bad. Timestamp is a message on it's own. Fixed the answer. – SergeyA Jul 15 '19 at 15:32
  • 1
    ... auto timestamp = new google::protobuf::Timestamp{}; timestamp->set_seconds(time(NULL)); timestamp->set_nanos(0); e.set_allocated_timestamp(timestamp); ... indeed fixes the problem. – Mike Jul 15 '19 at 15:35