The strings you allocate for a1[0]
and a1[1]
(each of which has space for 10 characters) are then being filled with 10 copies of either '#'
or '='
... which means that neither has an explicitly-set (and required) nul
terminator. Thus, the printf
call causes undefined behaviour.
To fix this, you can use the calloc
function to explicitly initialize the memory to zero, then only set one less than the buffer size copies of the character required (either by reducing this to 9
or increasing the allocation to 11
):
#include <stdio.h>
#include <stdlib.h>
int main()
{
char*** a2 = malloc(10 * sizeof(char**));
char** a1 = malloc(10 * sizeof(char*));
a1[0] = calloc(10, sizeof(char)); // Sets all characters in buffer to 'nul'
memset(a1[0], '#', 9); // This leaves the last ('nul') intact!
a1[1] = calloc(10, sizeof(char));
memset(a1[1], '=', 9);
a2[0] = a1;
printf("%s", a2[0][0]);
// Don't forget to free the memory you have allocated ...
free(a1[0]);
free(a1[1]);
free(a1);
free(a2);
return 0;
}
Also, you might like to read: Do I cast the result of malloc?