Lior Avramov
Lior Avramov

Reputation: 695

strlen of char* malloc

I have the following code

char *new_str;
int size_in_bytes;
int length;

size_in_bytes = 2*sizeof(char);
new_str = (char *)malloc(size_in_bytes);
length = strlen(new_str);

Expecting the length to be 2, actually it is 16. Can someone explain why?

Upvotes: 2

Views: 1029

Answers (1)

MattJ
MattJ

Reputation: 7924

strlen() returns the index of the first null-byte ('\0'), starting from the address you pass it. Strings in C typically always end with this character, to mark the end of the string.

strlen() does not return the length of the actual block of memory.

In your example the memory is uninitialized, and strlen() is reading past the end of your block of memory and into other parts of your program's heap, until it finds a null-byte.

Upvotes: 5

Related Questions