Composed without segmentation errors

I worked with an example from K & R, its cat utility for viewing files

#include <stdio.h>

main(int argc,char **argv){
      FILE *fp;
      void filecopy(FILE *,FILE *);

      if(argc==1)
           filecopy(stdin,stdout);
      else                           // accidentally mistyped
           while(--argv > 0)         // should have been --argc > 0
                if((fp=fopen(*++argv,"r"))==NULL){
                        printf("cat: can't open %s\n",*argv);
                        return 1;
                }else{
                        filecopy(fp,stdout);
                        fclose(fp);
                }
     return 0;
}
void filecopy(FILE *ifp,FILE *ofp)
{
      int c;
      while((c=getc(ifp))!=EOF)
            putc(c,ofp);
}

When compiling with gcc cat.c, and when I was running. /a.out cat.c from the terminal, all I had was some chinnesse characters and some readable text (names like _fini_array _, _ GLOBAL_OFFSET_TABLE_ etc.) and the garbage just went on until I pressed Ctrl + C, I wanted to ask why I did not have a segmentation error , because the program did not read each memory location from the argv start address? and I should not have rights to this?

+4
source share
1 answer

Let's look at these two consecutive lines:

    while(--argv > 0)
            if((fp=fopen(*++argv,"r"))==NULL){

, argv, . , argv , argv.

argv, undefined , . , , , .

, --argv undefined, , , , argv. , argv, , .

+3
source

All Articles