free *()作为参数

时间:2018-04-17 17:03:58

标签: c malloc free

晚上好,我生气了。我的程序在执行结束时向我显示“free():next size(fast)”。我怎么处理这个?我认为这是因为在某些时候变量名称不足以包含名称。可能是吗?

这是代码: 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);

 }

1 个答案:

答案 0 :(得分:1)

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

您需要空格来跟踪NUL字符('\0'

更改为

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

正如@TormundGiantsbane在评论中指出的那样,strcat(name, temp);

还需要更多的空间