Search code examples
cmallocstrlen

Why does strlen not work on mallocated memory?


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?


Solution

  • 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 mallocated block alone is not possible. Store the size in seperate variables like Lsize and Rsize.


    Notes:

    • don't cast the result of malloc
    • multiplying by sizeof(char) is redundant as sizeof(char) == 1
    • use free after malloc
    • the corresponding format specifier for size_t, a.k.a. "return type of strlen and the sizeof operator" is %zu; %d is used on ints1

    1 as @chux noted in the comments to this answer