1

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

4

2 回答 2

7

\0在字符串末尾缺少空终止符,因此strlen无法知道unsigned char *结束的位置。

实际上,它会在地址之后一直计数到您设置的最后一个字符,直到它到达一个\0.

于 2012-06-14T01:21:42.737 回答
2

strlen将根据终止字符计算长度,即 0 ( '\0')。

两种情况都是相似的:strlen寻找 0,但您只指定'\n'为“结尾”,它将读取该字符,直到找到终止 0,它可能会在不同的地方找到,这取决于什么“垃圾”内存恰好包含

处理未终止的字符串通常会导致分段错误,当读取过去的“字符串”访问尚未为项目分配的内存时,该错误将终止您的程序。

于 2012-06-14T01:22:00.817 回答