由于malloc()语法错误导致程序崩溃

struct nouedls { char * path; char * name; struct nouedls * suiv; }; typedef struct nouedls nouedls; typedef nouedls * listes; listes ajouters(listes ls, char * path , char* name) { nouedls * x=malloc(sizeof(x)); listes auxl; x->path=malloc(strlen(path)*sizeof(char)); x->name=malloc(strlen(name)*sizeof(char)); strcpy(x->path,path); strcpy(x->name,name); x->suiv=NULL; if (ls==NULL){ ls=x; } else { auxl=ls; while(auxl->suiv!=NULL) { auxl=auxl->suiv; } auxl->suiv=x; } return(ls); } void makepath(char* path){ char ch2 [400]; int i=0 ; int k=0 ; while (path[i]!='\n') { if (path[i]!='\\') { ch2[k]=path[i] ; i++ ; k++ ; } else { ch2[k]=path[i] ; k++ ; ch2[k]='\\' ; k++ ; i++ ; } } ch2[k]='\0' ; } void menu (char*path){ FILE *fp; char *fname = "MyScript.bat"; FILE *f ; listes menu=malloc(sizeof(menu)) ; char upath [400]; char name [260] ; menu=NULL ; if ((fp = fopen(fname, "wt")) == NULL) {fatal("Cannot open script file");} makebatfd(fp, "MyDirectory",path); if (fclose (fp)) {fatal("Cannot close script file");} system("MyScript.bat>menu.txt");//make the menu .txt file nom(path) ;//makes the name.txt file if ((fp = fopen("menu.txt", "r+")) == NULL) {fatal("Cannot open menu file");} if ((f = fopen("name.txt", "r+")) == NULL) {fatal("Cannot open name file");} printf("path") ; while (fgets(upath,400,fp)!= NULL ) { makepath(upath) ;//it handles the character '\' fgets(name,260,f) ; printf("%s",upath) ; menu=ajouters(menu,upath,name) ; printf("path") ; } if (fclose (f)) {fatal("Cannot close name file");} if (fclose (fp)) {fatal("Cannot close menu file");} } 

menufunction创建一个文件menu.txt ,其中包含文件路径和另一个文件名name.txt包含这些文件的名称。 我想把这些文件中包含的信息放在一个列表中使用它可以工作的函数但是在某一行它崩溃了(我只放了我怀疑的function,因为其他function完美)

我想,你需要改变

第1点:

 nouedls * x=malloc(sizeof(x)); 

 nouedls * x=malloc(sizeof(*x)); // *x == struct nouedls, x == struct nouedls * 

第2点:

 x->path=malloc(strlen(path)*sizeof(char)); 

 x->path=malloc(strlen(path) + 1); //+ 1 to hold the terminating null, sizeof(char) == 1 always. 

同样地。

此外,在使用返回的指针之前,您必须检查malloc()的返回值是否成功。