Incorrect Strlen value returned

I receiving an incorrect strlen value of a, it return 101 instead of 100, has anyone come across this error before? Has it been corrupted during conversion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

long MAX(long m, long n) {
	return m > n ? (m) : (n);
}

typedef unsigned char Uchar;

int main() {

	Uchar* a;
	Uchar* b;

	int a_size = 100;
	int b_size = 90;

	a = (Uchar*) malloc(100);
	b = (Uchar*) malloc(90);

	printf("%li\n", a_size);
	printf("%li\n", b_size);

	for (int i = 0; i < 100; i++) {
		a[i] = '3';
	}

	for (int j = 0; j < 90; j++) {
		b[j] = '4';
	}

	long c_size = (long)sizeof(unsigned char);
	a_size = (long) strlen((char*) a);
	b_size = (long) strlen((char*) b);

	long size = MAX(b_size, a_size);

	printf("%li\n", c_size);

	printf("%li\n", a_size);

	printf("%li\n", b_size);

	printf("%li\n", size);

	return 0;
}
The block of memory returned from malloc is uninitialised. You then fill those blocks of memory with a character, but never null terminate the sequence. strlen just counts the number of characters up to the first null. As you never set a null, strlen has marched off the end of your buffer and found a null somewhere else.

You should note that the resuts of this program are non-deterministic and will different results on different systems.

See:
http://www.cplusplus.com/forum/beginner/67300/#msg359320
The strlen function tells you how many chars there are from a pointer position, to the next zero value in memory. How do you know that the next zero value is after 100 chars? Where in your code did you write that zero value?

Edit: ninJAR!
Last edited on
Topic archived. No new replies allowed.