1

I was trying to code a c program that is given the name of a file by Command line and then opens the nano editor on the file through a system() call.

After having edited and saved the file, the c program sorts the file by first reading the file, sorting the contents and then writing to the file.

But I am getting segmentation error. Please help.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argcn,char **args)
{
char *filename=*(args+1);
char *command="nano";
strcat(command," ");
strcat(command,filename);
char *txt=".txt";
strcat(command,txt);
system(command);




int numbers[100];
int n=0;
FILE *fp;
fp=fopen(filename,"r+");
while(1>0)
{
  int num;
  int x=fscanf(fp,"%d",&num);
  if(x!=1)
    break;
  else
  {
    numbers[n]=num;
    n+=1;
  }
}
numbers[n]=-1;

int temp;
int temp1;
for(temp=0;temp<(n-1);temp++)
{
  for(temp1=(temp+1);temp1<n;temp1++)
  {
    if(numbers[temp1]<numbers[temp])
    {
      int t=numbers[temp1];
      numbers[temp1]=numbers[temp];
      numbers[temp]=t;
    }



  }

}
fclose(fp);
FILE *nfp;
nfp=fopen(filename,"w");
for(temp=0;temp<n;temp++)
{
  fprintf(nfp,"%d\n",numbers[temp]);
}
fclose(nfp);

}

1 Answers1

1

This code can lead to undefined behaviors

char *command="nano";
strcat(command," ");
strcat(command,filename);
char *txt=".txt";
strcat(command,txt);

Because command is 5 byte length filled with "nano\0" and you appending space " " and filename to memory after 'allocated' place. You need pre allocate command enough to hold nano command with file name. For example you can try:

char command[256];
strcat(command,"nano");
strcat(command," ");
strcat(command,filename);
char *txt=".txt";
strcat(command,txt);
Login
  • 105
  • 1
  • Yes; and I think there's a potential for `numbers` to overrun as well. Problems like this need a debugger, such as `gdb`, which will usually point out the exact line on which the problem arose. – Kevin Boone Sep 17 '20 at 20:21
  • Couple of nitpicks: (1) *"This code can lead to undefined behavior"* - you can remove the "can", this is 100% textbook undefined behavior as per the standard. (2) *"command is 5 byte length filled with "nano\0""* - that's not the exact reason actually, the reason is that `command` is a pointer to a string constant, and string constants are by definition immutable (or else the behavior is undefined). – Marco Bonelli Sep 17 '20 at 22:42