strcpy()有什么问题? (分段故障)

这段代码中的strcpy()有什么问题?

 void process_filedata(char *filename) { void* content; const char * buffer; char * temp; char * row; char * col; int lsize,buflen,tmp,num_scan; //num_scan - number of characters scanned int m=0,p=0,d=0,j=0; //m - machine, p - phase, d- delimiter, j - job FILE *file_pointer = fopen("machinetimesnew.csv","r"); if(file_pointer == NULL) { error_flag = print_error("Error opening file"); if(error_flag) exit(1); } fseek(file_pointer, 0 ,SEEK_END); lsize = ftell(file_pointer); buflen = lsize; rewind(file_pointer); // content = (char*) malloc(sizeof(char)*lsize); fread(content,1,lsize,file_pointer); buffer = (const char*) content; strcpy(temp,buffer); row = strtok(temp,"\n"); ............... ............... 

我收到了分段错误..

这里实际上有三个分段错误:

 fread(content,1,lsize,file_pointer); strcpy(temp,buffer); row = strtok(temp,"\n"); 

第一个是fread() ,它尝试写入内存,就您的进程而言,该内存尚不存在。

第二个是strcpy() ,(在第一个上解释)你试图复制到指向任何东西的指针。 没有为temp ,静态或动态分配内存(指针引用本身除外)。

通过改变temp看起来像这样(静态分配)修复此问题:

 char temp[1024]; 

或者使用malloc()为它动态分配内存(以及其他指针,因此它们实际指向某些content ),同样用于content 。 如果在编译时知道所需的缓冲区大小,请使用静态分配。 如果没有,请使用malloc() 。 “知道”是另一个问题的主题。

第三个是strtok() ,它将修改temp en situ (就地),这显然是不能做到的,因为temp从未被分配过。 无论如何,一旦strtok()完成,不要指望temp是相同的。 通过变量的名称,我假设你知道。

此外, 初始化指针与为其分配内存不同:

 char *temp = NULL; // temp is initialized char *temp = (char *) malloc(size); // temp is allocated if malloc returns agreeably, cast return to not break c++ 

最后,请养成在strcpy()上使用strncpy()的习惯,它更安全。

你没有为临时分配任何空间。 这是一个狂野的指针 。

strcpy没什么不对的。 你没有初始化temp

还有一个错误。 fread不会在缓冲区末尾添加一个空字符。 那是因为它只处理字节数组,而不处理以空字符结尾的字符串。 所以你需要做这样的事情:

 content = malloc(lsize + 1); fread(content,1,lsize,file_pointer); content[lsize] = 0; temp = malloc(lsize + 1); strcpy(temp, content); 

或这个:

 content = malloc(lsize); fread(content,1,lsize,file_pointer); temp = malloc(lsize + 1); memcpy(temp, content, lsize); temp[lsize] = 0; 

(另外,在实际代码中,你应该检查freadmalloc的结果。)

你没有为temp分配内存

char * temp尚未初始化,因此您没有为其分配任何内存。

尝试:

temp = (char *)malloc(SIZE);

但是, SIZE需要为temp分配大量内存

这段代码引起了我的兴趣:

 if(file_pointer == NULL) { error_flag = print_error("Error opening file"); if(error_flag) exit(1); } 

如果file_pointer为NULL,你不应该无条件退出吗?