Question

How does one properly allocate array of unsigned chars?

packet = (u_char*) malloc (20*sizeof(u_char)); //is it simmilar to u_char packet[20]?

I have 2 functions which are declared as follows

u_char *frame(bool type, char* srcmac, char* dstmac);
u_char *ip(bool type, char* srcip, char* dstip);

how can I concatenate those 2 unsigned chars? I tried memcpy, strcat[only for char].

u_char *concat(u_char *s1, u_char *s2) {

    u_char *result = (u_char*) malloc((sizeof(s1)+sizeof(s2)+1));//+1 for the zero-terminator

    memcpy(result, s1, sizeof(s1));
    memcpy(result, s2, sizeof(s2)); //I am overwriting result already and sizeof is size of pointer...
    return result;
}
Was it helpful?

Solution

You have:

u_char *concat(u_char *s1, u_char *s2) {
u_char *result = (u_char*) malloc((sizeof(s1)+sizeof(s2)+1));

This doesn't make any sense. Why do you care how big the pointers are? And how is this function supposed to concatenate two things without knowing how big they are? Also:

memcpy(result, s1, sizeof(s1));
memcpy(result, s2, sizeof(s2));

Should be:

memcpy(result, s1, s1_size);
memcpy(result + s1_size, s2, s2_size);

You have to track the sizes of the s1 and s2 objects yourself. I called those variables s1_size and s2_size, but they can be constants. Don't use sizeof on a pointer or you get the size of the pointer. The sizeof function tells you the size of a type, known at compile time.

Since this is C++, why not just use std::vector<unsigned char> and then + and += will work nicely. Otherwise, consider a struct that encapsulates both a pointer and a size_t.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top