I am beginner to C language and a thing that I can't understand very well is the use of malloc. So I decide to create this example. I would like to understand why it doesn't print out the buffer data and what is the best practice to do this.
#include <stdio.h> /* printf, scanf, NULL */
#include <stdlib.h> /* malloc, free, rand */
void f(char * buffer, int i) {
buffer = (char *) malloc(i+1);
if (buffer==NULL)
exit (1);
for (int n=0; n<i; n++)
buffer[n]=rand()%26+'a';
buffer[i]='\0';
}
int main ()
{
char * buffer;
f(buffer, 5);
printf ("Random string: %s\n",buffer);
free (buffer);
return 0;
}
Thanks