How can i check if i am using right the dynamic allocation in my C code. It is an assignment for uni. When i put my code in the auto corrector system of my professor i get an error for dynamic allocation. My code :
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <stdarg.h>
#include <sys/types.h>
#include <unistd.h>
#include <ctype.h>
int main( )
{
for(;;)
{
char *cmd,*splitcmd;
//*pr0,*pr1,*pr2 ;
size_t bufsize = 1024;
char pr1[bufsize];
char pr2[bufsize];
char pr0[bufsize];
//char pr3[40];
int i,j,nargc=0,characters;
char **cmdArray;
//size_t bufsize = 1024;
// size_t bufsizecmd =1024;
pid_t pid,wpid;
int status = 0;
char pr='$';
char exit1[10]="exit";
char *path;
path = getenv("PATH");
putchar(pr);
cmd = malloc(bufsize * sizeof*cmd);
characters = getline(&cmd,&bufsize,stdin);
//printf("cmd===> %s characters===> %d \n",cmd,characters);
if(cmd[characters-1]=='\n' )
{
cmd[characters-1]='\0';
characters--;
}
//printf("cmd===> %s characters===> %d \n",cmd,characters);
cmdArray = malloc(bufsize*sizeof*cmdArray );
for ( i = 0; i < bufsize; i++ )
{
cmdArray[i]=malloc(bufsize*sizeof*cmdArray );
}
splitcmd=strtok(cmd," ");
// printf(" cmd==== %s\n",cmd);
while((splitcmd))
{
strcpy(cmdArray[nargc],splitcmd);
if(cmdArray[nargc][(strlen(cmdArray[nargc]))-1]==' ')
cmdArray[nargc][(strlen(cmdArray[nargc]))-1]='\0';
//printf(" nargc====%d cmdArray===[%s] \n",nargc,cmdArray[nargc]);
nargc++;
splitcmd = strtok(NULL," ");
}
//printf(" pr0 %s \n",pr0);
//printf(" pr1 %s \n",pr1);
//printf(" pr2 %s \n",pr2);
strcpy(pr0,cmdArray[0]);
if (strcmp( pr0, exit1) == 0 )
{
//printf("---------->Eksodos apo to programma<---------- \n");
free(cmd);
return (0);
exit(0);
//return (0);
}
else
{
if ((pid=fork()) == 0)
{
if(nargc ==1 )
{
strcpy(pr0,cmdArray[0]);
char *argv[] = {path,NULL};
execvp(pr0,argv);
for ( i = 0; i < bufsize; i++)
{
free(cmdArray[i]);
}
free(cmdArray);
free(cmd);
exit(0);
}
else if(nargc==2)
{
strcpy(pr0,cmdArray[0]);
strcpy(pr1,cmdArray[1]);
char *argv[] = {pr0,pr1,NULL};
execvp(pr0,argv);
exit(0);
for ( i = 0; i < bufsize; i++)
{
free(cmdArray[i]);
}
free(cmdArray);
free(cmd);
exit(0);
}
else
{
strcpy(pr0,cmdArray[0]);
strcpy(pr1,cmdArray[1]);
strcpy(pr2,cmdArray[2]);
//printf("cmdddddddd****====%s \n",*cmdArray);
char *argv[] = {pr0,pr1,pr2,NULL};
execvp(argv[0],argv);
for ( i = 0; i < bufsize; i++)
{
free(cmdArray[i]);
}
free(cmdArray);
free(cmd);
exit(0);
}
}
wait(&status);
}
}
}