Noe Cano
Noe Cano

Reputation: 515

Number of Characters in a pointer of unsigned chars in C

I have a function that concatenates characters in a pointer and I need to return its size, but I can not get the total of characters, this is the function:

int function(unsigned char * dest)
{
    *dest++ = 0x12;
    *dest++ = 0x34;
    *dest++ = 0x56;
    *dest++ = 0x78;
    *dest++ = 0x9A;
    *dest++ = 0xBC;
    *dest++ = 0xDE;
    *dest++ = 0xFF;

    *dest++ = '\0';

    size_t len = strlen((char*) dest);

    return len;
}

This is how I occupy it:

unsigned char buffer[512];
int buffer_len = function(buffer);

The problem is that buffer_len is always zero and i expect to be 16.

Upvotes: 0

Views: 61

Answers (2)

dbush
dbush

Reputation: 224842

When you get to the strlen call, dest is pointing to one element past the null byte at the end of the string. This invokes undefined behavior since that byte and the ones after were never initialized.

You need to keep track of the original value of dest and subtract:

int function(unsigned char * dest)
{
    unsigned char *start = dest;
    *dest++ = 0x12;
    *dest++ = 0x34;
    *dest++ = 0x56;
    *dest++ = 0x78;
    *dest++ = 0x9A;
    *dest++ = 0xBC;
    *dest++ = 0xDE;
    *dest++ = 0xFF;

    *dest = '\0';

    return dest - start;
}

Upvotes: 5

Bathsheba
Bathsheba

Reputation: 234835

The behaviour of your code is undefined.

You are modifying the input pointer dest that you've passed as a parameter.

At the point of calling strlen((char*) dest), dest points to one past the NUL that you added. You cannot then predict the behaviour of strlen as it will be reading uninitialised elements of buffer.

The simplest fix is to take a copy of dest when you enter the function, and subract that original value from the final value of dest. That will be the string length.

Upvotes: 1

Related Questions