My C program has to parse a fixed-length message like this:
uint8_t message[8] = {80, 75, 73, 71, 1, 1, 1, 1};
another message could be:
uint8_t message[8] = {80, 75, 73, 71, 41, 42, 1, 1};
The message contains an ASCII string and 1 shows the end of string. So the actual length of the first message is 4 and the second message is 6.
I use this method to extract the message:
1. Counting the message length
2. Initializing a variable length array with this value.
3. Using memcpy to copy the bytes.
decoder.h
#ifndef DECODER_H_INCLUDED
#define DECODER_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#define LENGTH 100
void parse(uint8_t * message);
void get_address(char * addr, int size);
uint8_t get_size(void);
#endif // DECODER_H_INCLUDED
decoder.c
#include "decoder.h"
// Global variables in library
uint8_t parsed_message[LENGTH];
uint8_t len = 0;
void parse(uint8_t * message)
{
len = 0;
for (int i = 0; i < LENGTH; i++)
{
if (message[i] != 1)
{
parsed_message[i] = message[i];
len++;
}
else
{
parsed_message[i] = '\0';
len++;
break;
}
}
}
void get_address(char * addr, int size)
{
memcpy(addr, parsed_message, size);
}
uint8_t get_size(void)
{
return len;
}
In the main function:
#include <stdio.h>
#include <stdlib.h>
#include "decoder.h"
int main(void) {
uint8_t input[8] = {80, 75, 73, 71, 1, 1, 1, 1};
parse(input);
char addr[get_size()];
get_address(addr, get_size());
printf("==== %s ==== ADDRESS\n", addr);
return 0;
}
I use GCC compiler and C99 standard in ARM-Based 32-bit micro-controller.
My question is that is this method safe? Or I should use another approach.
#includes also. \$\endgroup\$