what is the correct way to get strlen for a unsigned char *
-
14-06-2021 - |
Question
My code below gave a different length for the unsigned char pointer I expect. I thought I should be getting 12 (or 13) or 0 (or 1) for pph and pphChar. What is my problem? I got different results for length and oneLength each time, when I repeat the run.
How can I get the length of pph?
Do I need to put a '\n' at the end to determine the length?
I use VS2010, XP and C++.
#include "stdafx.h"
#include <stdlib.h>
#include <Windows.h>
#include <stdio.h>
#include <tchar.h>
typedef unsigned char uint8_t;
int _tmain(int argc, _TCHAR* argv[])
{
int length;
int len = 13;
uint8_t *phh;
char * phhChar;
printf("assigned mem %d\n", sizeof(unsigned char)*len);
phh = (unsigned char *) malloc(sizeof(unsigned char)*len);
phhChar = (char *) malloc(sizeof(char)*len);
phh[0] = (unsigned char) '1';
phh[1] = (unsigned char) '2';
phh[2] = (unsigned char) '3';
phh[3] = (unsigned char) '4';
phh[4] = (unsigned char) '5';
phh[5] = (unsigned char) '6';
phh[6] = (unsigned char) '7';
phh[7] = (unsigned char) '8';
phh[8] = (unsigned char) '9';
phh[9] = (unsigned char) '0';
phh[10] = (unsigned char) '1';
phh[11] = (unsigned char) '2';
phh[12] = (unsigned char) '\n';
phhChar[0] = (char) '\n';
printf("size of char %d\n", sizeof(unsigned char));
length = strlen((const char*)phh);
int oneLength = strlen((const char*)phhChar);
printf("len %d\n", length );
printf("onelebgth %d\n", oneLength);
OUTPUT
assigned mem 13
size of char 1
len 32 - different each time
oneLength 32 - different each time
Solution
You are missing the null terminator \0
at the end of the string so strlen
is not able to know where the unsigned char *
ends.
Actually it keeps counting after the address to last character you set by looking until it reaches a \0
.
OTHER TIPS
strlen
will count the length based on the terminating character, which is 0 ('\0'
).
Both cases are similar: as strlen
is looking for a 0, but you only specified '\n'
as the "ending", it will read past that character until it finds that terminating 0, which it might find in different places, depending on what "garbage" the memory happens to contain
Handling unterminated strings can often end up with a segmentation fault that will terminate your program when reading past the "string" accesses memory that has not beem allocated for the project.