What is wrong with my code ?
Hi everyone @Middleware & OS , please what is wrong with my code ?
I'm using Arduino/ESP32 with FreeRTOS and I'm aware std::string isn't available. That's why I used
sprintf
to convert an int value to a string. Now I noticed that when I call sprintf
in the task function as follows ESP32 crashes and I can't find the reason.
6 Replies
Hmm, I think the issue with your code lies in the misuse of
sprintf
and memory management. The second argument of sprintf
should be a buffer wherein the result can be stored, not the length. This is causing undefined behavior. @Marvee AmasiAlso, you are making use of
new
to allocate memory but free
to deallocate it, which is incorrect. You should use delete[]
to free memory allocated with new[]
.Plus, In embedded environments, I think assert
may not be appropriate because it might halt the system.Perhaps you could try the code this way š:
Undefined behavior
Yeah that's why it crashes@Marvee Amasi your code is crashing mainly because of three mistakes you are making which are:
using the new operator to allocate memory for buf while you are freeing it using free(). This is incorrect and can lead to memory leaks or crashes. Since you are using C++, it is recommended to use new and delete for memory management.
secondly, In the sprintf call you are passing length + 1 as the buffer length argument. whereas the buffer length argument should be the size of the buffer, not the size of the string you are going to write into it. You can simply pass length as the buffer length.
thirdly, In the sprintf call, you are using a format specifier of %d for each version number. However, since the version numbers are uint8_t you should use the format specifier %hhu instead.
your code should look like this
š
Lol I have seen mistakes here