I honestly have no idea how the following even happens. Here is the code:
while(1)
{
char** line = read_command();
char* command = line[0];
char** parameters = malloc(100);
int i;
for(i = 0; i < pNum; i++) // pNum is a global var containing the number of words read from read_command()
{
parameters[i] = line[i];
printf("%i: %s", i, parameters[i]);
}
printf("%s\n", parameters[0]);
parameters[0] = "/usr/bin/";
strcat(parameters[0], command);
printf("%s\n", command);
printf("%s\n", parameters[0]);
if(fork() != 0)
waitpid(1, &status, 0);
else
execve(parameters[0], parameters, NULL);
}
read_command() returns a char** that is basically an "array" to the string that was entered, and each char* contains a word. Like if I enter "hello people of earth" the result would be ["hello", "people", "of", "earth"]. This fucntion always works.
upon the first iteration everything works just as expected. example, when I type "date" the output is as follows:
0: date
date
date
/usr/bin/date
and then the date is displayed
but upon the second iteration if i use "date" as the input again the output is as follows:
0:date
edate
/usr/bin/datedate
and the date command is not issued
the second printf statement always prints "e" after the first iteration even if I print a constant string like "hello". and then the parameters[0] somehow has 2 "date" in it even though the command pointer has only 1 "date".
And after the third iteration the program does not wait for user input, it just loops non stop and displays "PM: warning, process table is full!"
What could possibly cause this?
I am working in MINIX 3.1.0 with the cc compiler for C
EDIT: the read_command():
char* line = malloc(), * linep = line;
size_t lenmax = 100, len = lenmax;
int c;
int currPos = 0;
int currParam = 0;
int i;
char** parameters = malloc(100);
if(line == NULL)
return NULL;
while(1)
{
c = fgetc(stdin);
if(c == EOF) || c == '\n')
break;
if(--len == 0)
{
char* linen = realloc(linep, lenmax *= 2);
len = lenmax;
if(linen == NULL)
{
free(linep);
return NULL;
}
line = linen + (line - linep);
linep = linen;
}
if((*line++ = c) == '\n')
break;
}
*line = '\0'; // everything up to this point i got from this link: http://stackoverflow.com/a/314422/509914
parameters[currentParam] = malloc(100);
for(i = 0; i < strlen(linep); i++);
{
if(isspace(linep[i]) || line[i] == EOF)
{
parameters[currParam][currPos] = '\0;
currPos = 0;
parameters[++currParam] = malloc(100);
}
else
parameters[currParam][currPos++] = line[i];
}
parameters[currParam][currPos] = '\0';
pNum = currParam + 1;
return parameters;