You have a memory leak if the user types more than 16 things. First of all, set every element of p to zero at the start. Then before you malloc(), check to see if p[pindex] is NULL. If it is, only then do you have to malloc().
To adjust pindex back to 15 for the last element, I would recommend an extra variable to calculate the last index.
Here's an altered version of your code:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *p[16] = { NULL };
int pindex = 0, plast;
while(1)
{
if(!p[pindex])
{
p[pindex] = (char *)malloc(sizeof(char)*128);
if(!p[pindex])
{
printf("Out of memory.\n");
break;
}
}
fgets(p[pindex], 128, stdin);
/* if(!strcmp(p[pindex], "break")) break; */
plast = (pindex == 0) ? (15) : (pindex - 1);
if((pindex == 0) && (!p[15]))
{
printf("There is no last item\n");
}
else
{
printf("Last thing you typed: %s\n", p[plast]);
}
pindex = (pindex + 1) % 16;
}
for(pindex = 0;pindex < 16;pindex++)
{
free(p[pindex]);
}
return 0;
}