-1

I am writing a program to open a file (say "input_file"), manipulate its contents and then output it to another file ("manipulated-input_file")

I have done this with strcpy and strcat in the following way:

char t-filename[]="Manipulated-", filename[50], td-filename[50];
memset ( filename, '\0', FILE_NAME);

printf("Please enter the filename - \n");
scanf( "%30s", filename );
strcpy(td-filename,filename);
strcat(t-filename,td-filename);
printf("%s\n", t-filename);

Now printf functions prints the t-filename as "Manipulated-input_file"

After this part, I have a section where I open "input_file" and do something.

fptr = fopen(filename, "r");
while ( fgets (line, sizeof line, fptr) != NULL)
{
 ...do something...
}
fclose(fptr);

Later I wanted to open a file with name 't-filename' at the end of the code:

tptr = fopen(t-filename, "w");
fprintf(tptr,"something");
fclose(tpr); 

When I compile this code I am getting "Segmentation fault (core dumped)".

I do not know what went wrong. Can somebody help?

JohnP
  • 109
  • 1
  • 10

2 Answers2

4

transfilename doesn't have enough space to hold additional items added there by strcat(transfilename,translatedfilename);. It's already full with "Translated-" since [] gives you the exact amount of characters in the initializing string, plus a null terminator.

You need to either change it to char transfilename [LARGE_ENOUGH] or use dynamic memory allocation to change the size in run-time.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Can you tell me how can I set dynamic memory in this case? Does it mean that I have to use char transfilename[SIZE] after reading the 'filename'? – JohnP Jun 16 '20 at 10:50
2

strcat(t-filename,td-filename);

t-filename is not large enough to accommodate the result and it is an Undefined Behaviour.

same here

strcat(transfilename,translatedfilename);

transfilename is not large enough to accommodate the result and it is an Undefined Behaviour.

0___________
  • 60,014
  • 4
  • 34
  • 74