在VC ++ 2008中运行程序时出现未处理的异常

时间:2012-01-17 09:29:20

标签: c

我试图在目录中打开一个二进制文件并相应地执行操作。我怀疑这一行......这不是正确的表示方式来处理下面的逻辑。

int main(int argc, char* argv[])
{
  int k=0;
  FILE *fp;
  unsigned char cd[255];
  unsigned long cd1[500];
  char *buffer;
  unsigned long sa=80044;
  int j=0,i=0,n=0;
  DIR *dir;
  struct dirent *direntry; //could be a file, or a directory

  dir = opendir("C:/Documents and Settings/Administrator/Desktop/vicky");
  if(!dir) {
  printf("Error: directory did not open!\n");
  return 1;
  }

  while((direntry=readdir(dir))!=NULL) {
  if(++k < 100)
  {
     printf("%s\n",direntry->d_name);
     sprintf(buffer,"%s",direntry->d_name);//here i got the unhanded exception.
     fp=fopen("buffer","rb");
     sa=sa-44;
     sa=sa/8;

  if(fp==NULL)
 {
   printf("file not found!");
 }
 else
      {
       for(j=0;j<(sa);j++)
       {
           for(i=0;i<8;i++)
           {
               cd[i]=fgetc(fp);//get each character from file 

              // printf("%c",cd[i]);

           }
           if(i==8)//if the i is 8 the character then do the following,just read 8 bytes  and then calculate the cd1.
           {
                sa=sa-8;
               cd1[j]=(cd[6] * 65536 + cd[5] * 256 + cd[4]);//multiply the positional weightage and calculate the cd1,which contains the 7 digits decimal value.

               //if((cd1[j]> 0x7FFFFF)&&(cd1[j]<=0xFFFFFF))

                 //cd1[j]=cd1[j]- 0xFFFFFF;
                 //cd1[j]=cd1[i] * -1;

           }
         printf("completes first 8 bytes read:%d - %d",j,cd1[j]);//print j and cd1[j] value in console window

       }
      fclose(fp);//close the file
   }


  }
  if((strcmp(direntry->d_name, "text.txt"))==0) {
     printf("\nThe %s file has been found\n",direntry->d_name);

     k=-99;  //just a flag value to show the file was found
     break;
   }

  }
  if(k!=-99)
  printf("\nThe test.txt file was not found\n");

  closedir(dir);

  printf("\n");
  getchar();
  return 0;

 }

这是我得到的错误:READ_TEXT.exe中0x1029a189(msvcr90d.dll)的未处理异常:0xC0000005:访问冲突写入位置0xcccccccc.Kindly让我任何建议读取“direntry-&gt; d_name”文件名来处理以上逻辑。

6 个答案:

答案 0 :(得分:0)

buffer未分配。 sprintf()基本上是在试图写“无处”。

目标变量需要使用malloc在堆上分配,或者在堆栈上将其使用限制在当前范围内。

答案 1 :(得分:0)

您只声明了char * buffer,而不是使用malloc()为它分配内存。

答案 2 :(得分:0)

你的问题是一个未初始化的指针。

使用malloc初始化指针或尝试数组

char buffer[1024];

答案 3 :(得分:0)

为简单起见,将字符缓冲区设为普通数组:

char buffer[1024];

这样你肯定会把记忆放在一边准备好使用。如果您的平台提供,则应使用snprintf()

答案 4 :(得分:0)

变化

char * buffer;

char buffer[MAX_PATH];

或类似的东西。

答案 5 :(得分:0)

U必须为缓冲区变量分配内存。 char * buffer;声明没有分配任何内存,所以我可以 任何数据。

所以你试试吧 聊天缓冲区[//缓冲区长度];

或char * buffer = new char(// buffer length);

或char buffer =(char )malloc(//缓冲区长度);

以上声明将分配内存并修复您的问题。