Memory allocation problem
I've got this memory allocation problem, can't seem to figure it out:
Code:
#include <ctype.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buf[10];
char *p[100];
int i = 0;
while(fgets(buf,sizeof(buf),stdin))
{
p[i] = malloc(20);
p[i] = buf;
i+=1;
}
for(i=0; i<3; i++)
{
printf("%s",p[i]);
}
return 0;
}
If I type
john
pavel
vlad
on the input,
it prints
vlad
vlad
vlad
on the output ?
What am doing wrong ? I don't understand, since I allocate 20 bytes for each spot in the array.
Can someone help me out ?
thanks