I've a problem with the use of malloc, memset and free, which doesn't work as expected. The problems is with the latest function printf, instead of printing "test", it prints some weird characters and then test, something like "@#°test". Can you expalin me why? I've noticed that everything works fine if I do a memset after the second malloc. Also, I really don't get why everything works fine if I don't call the function "function()", even without a memset
Here's my code:
#define size 10
void function(){
...
...other code...
...
char *b=malloc(size);
read(file_ds,b,size); //file_ds stands for file descriptor, correctly opened with open function.
memset(b,0,size);
free(b);
}
void main(){
...
...other code...
...
function(); //If I don't call this, everything works fine, even without a memset
char *c=malloc(size);
strcat(c,"test");
printf("%s",c);
}
strcat
expects that the address you give it points to a valid string, and it will attempt to find the end of that string by looking for a zero byte. Your pointer, however, points into uninitialized memory, and it is undefined behaviour to attempt to read it.
Changing malloc
to calloc
provides you with initialized memory. However, that may be overkill, since it's enough to have an initialized initial segment, which you can achieve like thisL
char *c = malloc(size);
c[0] = '\0';
strcat(c, "test"); // OK