views:

10643

answers:

7

I have a variable

unsigned char* data = MyFunction();

how to find the length of data?

+4  A: 

assuming its a string length = strlen( char* ); but it doesn't seem to be....so there isn't a way without having the function return the length.

kenny
+8  A: 

You will have to pass the length of the data back from MyFunction. Also, make sure you know who allocates the memory and who has to deallocate it. There are various patterns for this. Quite often I have seen:

int MyFunction(unsigned char* data, size_t* datalen)

You then allocate data and pass datalen in. The result (int) should then indicate if your buffer (data) was long enough...

Daren Thomas
If MyFunction is supposed to pass a pointer back to the caller (as in the example), the first argument should be unsigned char**
Mathias
No, he's passing the length back. The buffer is allocated by the caller and passed to the function.
paxdiablo
A: 

As said before strlen only works in strings NULL-terminated so the first 0 ('\0' character) will mark the end of the string. You are better of doing someting like this:

unsigned int size;
unsigned char* data = MyFunction(&size);

or

unsigned char* data;
unsigned int size = MyFunction(data);
+1  A: 

Now this is really not that hard. You got a pointer to the first character to the string. You need to increment this pointer until you reach a character with null value. You then substract the final pointer from the original pointer and voila you have the string length.

int strlen(unsigned char *string_start)
{
   /* Initialize a unsigned char pointer here  */
   /* A loop that starts at string_start and
    * is increment by one until it's value is zero,
    *e.g. while(*s!=0) or just simply while(*s) */
   /* Return the difference of the incremented pointer and the original pointer */
}
DrJokepu
A: 
#include <stdio.h>
#include <limits.h>  
int lengthOfU(unsigned char * str)
{
    int i = 0;

    while(*(str++)){
     i++;
     if(i == INT_MAX)
         return -1;
    }

    return i;
}

HTH

plan9assembler
A: 

The original question did not say that the data returned is a null-terminated string. If not, there's no way to know how big the data is. If it's a string, use strlen or write your own. The only reason not to use strlen is if this is a homework problem, so I'm not going to spell it out for you.

Larry Gritz
+1  A: 

There is no way to find the size of (unsigned char *) if it is not null terminated.

mch