Reputation: 63
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
Upvotes: 2
Views: 3542
Reputation: 727067
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);
Upvotes: 8
Reputation: 134396
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 bys2
(including the terminating null character) to the end of the string pointed to bys1
. The initial character ofs2
overwrites the null character at the end ofs1
.
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.
Upvotes: 3
Reputation: 215305
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);
Upvotes: 0