Your
getcommand
does a a little mess with the buffers.
While looping in the do statement, buffer is made pointing to a buffer that is enlarged as characters are read.
After exiting the loop, the *(buffer++)='\0' statement in fact shift the buffer pointer by one after placing a '\0' thus giving
|0|_|_|_|_|_|_|_|_|_|_|
^buffer
The proper statement should have probably been
buffer[count]='\0'
, giving
|_|_|_|_|_|_|_|_|_|0|
^buffer
But beware that your call to
realloc
should allocate
(count+1)*sizeof(x)
, otherwise you will have no space to store the '\0' character at end.
At this point, by returning
buffer
, you give the caller the responsibility to free what have been allocated.
You have to call
free(cmd)
before loping back to a new
getcommand
, and before returning from
main
.
int main(){
char *cmd;
while(1)
{
cmd = getcommand();
if (cmd[0] == 'q')
{
printf("exit character has been detected\n");
break;
}
printf("the command is %s\n",cmd);
free(cmd);
}
free(cmd);
return 0;
}