In order to better understand the differences between malloc and calloc I tried to find an example where malloc leaves the memory uninitialized/reuses it from a previous allocation.
I came across the SO question Why does malloc initialize the values to 0 in gcc?
I tried to replicate the exampe, but allocating a char array instead and setting a single value. However, it seems malloc works in that case, but why?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main(void) {
    // this shows, that malloc does not initialize memory
    {
        double *a = malloc(sizeof(double)*100);
        *a = 100;
        printf("%f\n", *a);
        free(a);
    }
    {
        double *a = malloc(sizeof(double)*100);
        printf("%f\n", *a);
        free(a);
    }
    // tried the same with chars, but my example doesn't work
    {
        char *ptr = malloc(sizeof(char) * 10);
        ptr[0] = 'a';
        printf("%s\n", ptr);
        free(ptr);
    }
    {
        char *ptr = malloc(sizeof(char) * 10);
        printf("%s\n", ptr);
        free(ptr);
    }
    return 0;
}
Output:
$ clang -ggdb memset_test.c
$  ./a.out
100.000000
100.000000
a
<empty string>
I can't see the difference, why does the first exable using doubles work, but not mine?
 
     
     
     
    