cmallocstrcatgarbage

malloc puts "garbage" values


how can i prevent or bypass the garbage valus malloc puts in my variable? attached the code and the output! thanks!

#include <stdio.h>
#include "stdlib.h"
#include <string.h>

int main() {
    char* hour_char = "13";
    char* day_char = "0";
    char* time = malloc(strlen(hour_char)+strlen(day_char)+2);
    time = strcat(time,day_char);
    time = strcat(time,"-");
    time = strcat(time,hour_char);
    printf("%s",time);
    free(time);
}

this is the output i get:

á[┼0-13

Solution

  • The first strcat is incorrect, because malloc-ed memory is uninitialized. Rather than using strcat for the first write, use strcpy. It makes sense, because initially time does not have a string to which you concatenate anything.

    time = strcpy(time, day_char);
    time = strcat(time, "-");
    time = strcat(time, hour_char);
    

    Better yet, use sprintf or snprintf:

    snprintf(time, sizeof(time), "%s-%s", day_char, hour_char);