This question may not make sense without the entire code but I am going to try my best to explain it. As a bit of background the code is a snippet from the OpenThread project on GitHub but I believe that standard c/c++ principles still apply here.
The purpose of the code is to append a piece of data (in this case a string) onto an OpenThread (ot) message. As arguments it takes an otMessage, a buffer (with the data) and the length of the buffer to be copied into the otMessage. I am not really sure how otMessageAppend
works and it is completely possible that the error is in the way that it reads the buffer, if this is the case nothing can be done about it.
The following c++ code was the starting point:
char command[] = "abcdef";
SuccessOrExit(error = otMessageAppend(message, &command, (uint16_t)strlen(command)*sizeof(char)));
When receiving the message at the other end I get abcdef
When passed abcdef
as argv[4]
this code works perfectly:
char command[strlen(argv[4])+1];//+1 for the null terminator
strcpy(command, argv[4]);
SuccessOrExit(error = otMessageAppend(message, &command, (uint16_t)strlen(command)*sizeof(char)));
However trying to allocate the memory using malloc
causes garbage to come out the other end (the correct number of bytes but not the correct data):
char *command;
command = (char *) malloc(strlen(argv[4])+1);
strcpy(command, argv[4]);
SuccessOrExit(error = otMessageAppend(message, &command, (uint16_t)strlen(command)*sizeof(char)));
I have a few questions about this:
- Is there anything wrong with declaring memory using
char array[size]
from what I understand the difference is that using[]
will allocate memory in the stack whereasmalloc
allocates the memory in the heap. - If I should be using
malloc
how can I ensure that the correct piece of memory will get "appended to the message" and not just garbage
If its vital to know how otAppendMessage
works I can dig through the source code and find it.