dvidelabs / flatcc

FlatBuffers Compiler and Library in C for C
Apache License 2.0
631 stars 180 forks source link

Creating string fails. #234

Closed mtrzas closed 2 years ago

mtrzas commented 2 years ago

I get this error message when I create a flatbuffers string:

malloc(): corrupted top size

Here is my code:

flatcc_builder_t builder, *B;

B = &builder;
flatcc_builder_init(B);

flatbuffers_string_ref_t state = flatbuffers_string_create_str(B, "bla");

Thank you for your help :)

mtrzas commented 2 years ago

I also tried already the other methods for creating a flatbuffers string like:

flatbuffers_string_ref_t state = flatbuffers_string_create_str(B, "bla", sizeof("bla);

and they are also not working for me

mtrzas commented 2 years ago

The flatcc_builder_init returns -1

mikkelfj commented 2 years ago

Yes, it won't work when init fails. I don't think the problem is in the create_str call in itself.

But I don't know why init fails - might depend on your platform. It could also be a bug earlier in your program where the heap is already corrupted.

mikkelfj commented 2 years ago

For example, if the builder object is an auto variable on the C stack and you keep the pointer after it goes out of scope. Depending on your actual implementation. I can't tell from what you have shown.

mtrzas commented 2 years ago

Yes it's an error on my side. I didn't find the error but I tried to do this at the start of the program and there it works :)

I really appreciate your help, thank you!

I want to use flatcc inside a pthread. Do I need to watch out for something specific that can happen or that shouldn't happen?

mikkelfj commented 2 years ago

pthread: You can reuse the samme builder context repeatedly one buffer at a time in the same thread, using reset in between. This reuses allocated memory. You cannot do this across threads. However, you can have a separate builder for each thread.

You can also share a builder across threads, but then you must synchronize, which is usually not worthwhile, but possible as with all other data structures. You would do this if multiple threads contribute to the content of the same buffer.

You would preferably not create a new builder on every new buffer, but it doesn't matter that much. So it may be convenient start a thread for every new buffer and init a builder at the same time. Basically init is just a few allocations.

mikkelfj commented 2 years ago

BTW: advanced use case: if you create a lot of content in different threads, you could create separate buffers for each thread and then clone parts of each buffer into a new final buffer in a single thread.

mtrzas commented 2 years ago

Thank you for your help and the detailed information!