Search code examples
cmallocfree

free() of a char* passed in an execve as parameter


Good evening, I'm getting mad with this. My program shows me "free(): invalid next size (fast)" at the end of the execution. How can I handle this? I think it's because at some point the variable name is not enough large to contain the name. Could it be?

This is the code: mamt.c

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <time.h>

int main(int argc, char *argv[]){
   srand((unsigned)time(NULL));
   char tmp;
   char** args=(char**)malloc(3*sizeof(char*));
   for(int i =0;i<3;i++){
       args[i]=(char*)malloc(10*sizeof(char));
   }
   char* name = (char*) malloc(10*sizeof(char));
   char* temp = (char*) malloc(10*sizeof(char));
   strcpy(name,"ABCDEFGHIL");

   register int i;
   for(i=0;i<20;i++){
       switch(fork()){     
          case -1:
            perror("Fork failed");
            exit(1);
          case 0:
            strcpy(args[0],"child_process");
            strcpy(args[1],name);
            args[2]=NULL;
            execve("./child_process",args,NULL);
            fprintf(stderr, "%s: %d. Error #%03d: %s\n", __FILE__, 
            __LINE__, errno, strerror(errno));
            exit(EXIT_FAILURE);
          default:
            tmp = (65+rand()%26);
            sprintf(temp, "%c", tmp);
            strcat(name,temp);
            sleep(1); 
       }
   }
  free(name);
  free(temp);
}

child_process.c

  #include <fcntl.h>
  #include <unistd.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <errno.h>
  #include <string.h>


int main(int argc, char *argv[]){
   char * name=(char*)malloc(100*sizeof(char));

   if(argc==2){
       strcpy(name,argv[1]);
       printf("My name is : %s\n",name);
   }else{
       exit(1);
   }

   free(name);
   exit(0);

 }

Solution

  • char* name = (char*) malloc(10*sizeof(char));
    ...
    strcpy(name,"ABCDEFGHIL");
    

    You need space for the trailing NUL character ('\0')

    Change to

    char *name = malloc(11); /* Don't cast malloc, and char is always 1 byte */
    

    And as pointed out by @ TormundGiantsbane in comments, you also need more space for this concat in strcat(name, temp);