2

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
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
JOSI
  • 63
  • 1
  • 5

3 Answers3

7

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:

sprintf(time, "%s-%s", day_char, hour_char);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

First of all, quoting C11, chapter 7.22.3.4 (emphasis mine)

The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

So, the content of the memory location is indeterminate. That is the expected behaviour.

Then, the problem starts when you use the same pointer as the argument where a string is expected, i.e, the first argument of strcat().

Quoting chapter 7.24.3.1 (again, emphasis mine)

The strcat function appends a copy of the string pointed to by s2 (including the terminating null character) to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1.

but, in your case, there's no guarantee of the terminating null in the target, so it causes undefined behavior.

You need to 0-initialize the memory (or, at least the first element of the memory should be a null) before doing so. You can use calloc() which returns a pointer to already 0-initialized memory, or least, do time[0] = '\0';.

On a different note, you can also make use of snprintf() which removes the hassle of initial 0-filling.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

strcat expects to get passed a null-terminated C string. You pass random garbage to it.

This can easily be fixed by turning your data into a null-terminated string of length 0.

char* time = malloc(strlen(hour_char)+strlen(day_char)+2);
time[0] = '\0';
time = strcat(time,day_char);
Lundin
  • 195,001
  • 40
  • 254
  • 396