I wrote the following code:
[all the required initialization]
printf("longueur de mid: %d\n",mid);
L = (char*) malloc((mid)*sizeof(char));
printf("longueur de L: %d\n",strlen(L));
[data treatment and free()]
And with the printf
I got this result:
longueur de mid: 2
longueur de L: 3
Why do the outputs differ?
strlen
iterates until a null byte is found. malloc
leaves the allocated space uninitialized, so a null byte may occur randomly. After all, it's undefined behavior due to the access of uninitialized memory.
Determining the size of a malloc
ated block alone is not possible. Store the size in seperate variables like Lsize
and Rsize
.
Notes:
malloc
sizeof(char)
is redundant as sizeof(char) == 1
free
after malloc
size_t
, a.k.a. "return type of strlen
and the sizeof
operator" is %zu
; %d
is used on int
s11 as @chux noted in the comments to this answer