The strlen of the char array is larger than its size. How to avoid?

I defined an array:

char arr [1480];

Now I read exactly 1480 characters from the file and placed it in arr (making arr [i] = c). I know 1480 characters because I use a while loop to read one char ar time (istream.get ()) and stops when incremental index = 1480.

However, after that, I make strlen (an array) and it returns 1512. How did it happen? This only happens in some cases, but not in all cases, although every time I read from a file, I always read up to 1480 characters.

My doubt is that a single char can take more than 1 units (units returned by strlen (arr)). If so, how can I fix this?

thank

PS: I used to ask a problem that my pointer is getting garbage, and this is the reason when I have a buffer (arr) of length> 1480.

0
source share
2 answers

The size of the array must include a line terminator. Since you are accurately reading the size of the array, you cannot (and do not add) add a line terminator. The function strlenand all other string functions use the end of line character to find the end of the line. If he will not, he will continue until he finds him.

If you can have no more than 1480 characters per line, you should have an array of size 1481, the last of which is a line terminator '\0'.

+6

?

char arr[1481]=0x00; //define all the array with string terminator
memcpy(arr,BufCopyFrom, 1480); //BufCopyFrom is the Buffer being copied and specified to copy 1480 bytes.

, .

0

Source: https://habr.com/ru/post/1668687/


All Articles