user3614276
user3614276

Reputation: 1

Reading in File, Segmentation Fault

Why is this giving me a 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);

I'm trying to get two file names such that if the argument parameter is test, file one will be test.tlb and file two will be test.pt.

Upvotes: 0

Views: 87

Answers (1)

Mahonri Moriancumer
Mahonri Moriancumer

Reputation: 6003

There are a couple instances in the question code where uninitialized pointers ('file' and 'file2') are inappropriately referenced (as indicated by 'wildplasser' and 'Red Alert').

Here is how I would 'fix' the code:

#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);
   }

Upvotes: 1

Related Questions