有什么不对的strcpy()? (分段故障) [英] What's wrong with strcpy()? (Segmentation fault)

查看:145
本文介绍了有什么不对的strcpy()? (分段故障)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是错的的strcpy()在这个code?

What is wrong with strcpy() in this code?

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");
  ...............
  ...............

我得到一个分段错误。

I am getting a segmentation fault..

推荐答案

有实际上这里的的段错误:

There are actually three segmentation faults here:

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

第一个是 FREAD()这是试图写入到不存在,只要你的进程而言的记忆。

The first one is fread() which is attempting to write to memory that does not yet exist as far as your process is concerned.

第二个是的strcpy(),(上接第阐述),您正试图复制到指向任何一个指针。没有记忆(比指针引用本身以外)已被分配给温度,静态或动态。

The second one is strcpy(), (expounding on the first) you are attempting to copy to a pointer that points to nothing. No memory (other than the pointer reference itself) has been allocated for temp, statically or dynamically.

通过改变温度看起来像这样(静态分配)修复此

Fix this via changing temp to look like this (allocating it statically):

char temp[1024];

或者使用的malloc()内容。如果你的知道的在编译时所需要的缓冲区大小,使用静态分配。如果没有,用的malloc()。 '知道'是另外一个问题的主题。

Or use malloc() to dynamically allocate memory for it (as well as your other pointers, so they actually point to something), likewise for content. If you know the needed buffer size at compile time, use static allocation. If not, use malloc(). 'Knowing' is the subject of another question.

第三个是的strtok(),这是要修改温度连接原位(的地方),它显然不能这样做,因为温度从未分配的。在任何情况下,不要指望温度来一次的strtok()与它做了同样的。由变量的名字,我想你知道。

The third one is strtok() , which is going to modify temp en situ (in place), which it obviously can not do, since temp was never allocated. In any event, don't expect temp to be the same once strtok() is done with it. By the name of the variable, I assume you know that.

此外,初始化的一个指针的的同样的事情为它分配内存:

Also, Initializing a pointer is not the same thing as allocating memory for it:

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

最后,请让使用函数strncpy() strcpy的习惯(),它更安全。

这篇关于有什么不对的strcpy()? (分段故障)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆