什么是错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");
...............
...............
Run Code Online (Sandbox Code Playgroud)
我收到了分段错误..
这里实际上有三个分段错误:
fread(content,1,lsize,file_pointer);
strcpy(temp,buffer);
row = strtok(temp,"\n");
Run Code Online (Sandbox Code Playgroud)
第一个是fread()尝试写入内存,就您的进程而言尚不存在.
第二个是strcpy(),(在第一个中阐述)你试图复制到指向任何东西的指针.没有为temp静态或动态分配内存(指针引用本身除外).
通过更改temp看起来像这样(静态分配)修复此问题:
char temp[1024];
Run Code Online (Sandbox Code Playgroud)
或者用malloc()它为它动态分配内存(以及你的其他指针,所以它们实际指向某些东西),同样适用于content.如果在编译时知道所需的缓冲区大小,请使用静态分配.如果没有,请使用malloc()."了解"是另一个问题的主题.
第三个是strtok(),它将修改temp 原位(就地),这显然是不能做的,因为temp从未分配过.无论如何,temp一旦strtok()完成它,不要期望是相同的.通过变量的名称,我假设你知道.
此外,初始化的指针是不一样的东西为它分配内存:
char *temp = NULL; // temp is initialized
char *temp = (char *) malloc(size); // temp is allocated if malloc returns agreeably, cast return to not break c++
Run Code Online (Sandbox Code Playgroud)
最后,请与我们使用的习惯strncpy()上strcpy(),它更安全.
strcpy没什么不对的.你还没有初始化temp.