读取文件,分段错误

时间:2014-05-07 23:33:18

标签: c segmentation-fault

为什么这会给我一个分段错误?

int main(int argc, char**argv)
{
printf("File name: %s\n", argv[1]);
char *file;
strcpy(file,"");
strcat(file,argv[1]);
strcat(file,".tlb");
char *file2;
strcpy(file2,"");
strcat(file2,argv[1]);
strcat(file2,".pt");
printf("\nfile One: %s\n", file);
printf("\nfile two: %s\n", file2);

我正在尝试获取两个文件名,如果参数参数为test,则文件一为test.tlb,文件二为test.pt。

1 个答案:

答案 0 :(得分:1)

问题代码中有几个实例未正确引用未初始化的指针('file'和'file2')(如'wildplasser'和'Red Alert'所示)。

以下是我将“修复”代码的方法:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc, char *argv[])
   {
   char  *fileName1=NULL;
   char  *fileName2=NULL;
   int    rCode=0;

   /* Validate caller arg(s) */
   if(argc < 2)
      {
      rCode=EINVAL;
      fprintf(stderr, "No file name specified.\n");
      goto CLEANUP;
      }

   /* Use snprintf() to calculate the number of bytes to 'malloc()'
    * to 'filename1' (including the '\0' termination character)
    * and then attempt to 'malloc()' the memory.
   */ 
   fileName1=malloc(snprintf(NULL, 0, "%s.tlb", argv[1]) + 1);
   if(NULL==fileName1)
      {
      rCode=ENOMEM;
      fprintf(stderr, "malloc() failed.\n");
      goto CLEANUP;
      }

   /* Compile the fileName1 string into 'malloc()'ed memory. */  
   sprintf(fileName1, "%s.tlb", argv[1]);

   /* Use snprintf() to calculate the number of bytes to 'malloc()'
    * to 'filename2' (including the '\0' termination character)
    * and then attempt to 'malloc()' the memory.
   */
   fileName2=malloc(snprintf(NULL, 0, "%s.pt", argv[1]) + 1);
   if(NULL==fileName2)
      {
      rCode=ENOMEM;
      fprintf(stderr, "malloc() failed.\n");
      goto CLEANUP;
      }

   /* Compile the fileName2 string into 'malloc()'ed memory. */
   sprintf(fileName2, "%s.pt", argv[1]);

   /* Print the resulting filenames. */
   printf("\nFilename one: \"%s\"\n", fileName1);
   printf("\nFilename two: \"%s\"\n", fileName2);

   /* Free memory back to the heap. */
CLEANUP:

   if(fileName2)
      free(fileName2);

   if(fileName1)
      free(fileName1);

   return(rCode);
   }