LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   strcat segmentation fault (https://www.linuxquestions.org/questions/programming-9/strcat-segmentation-fault-492809/)

mesh2005 10-16-2006 06:49 AM

strcat segmentation fault
 
I made a simple c program to create some files on the form sample1, sample2, sample3 ,....
I got segementation fault, I don't know why. Can anyone help me to do it using C (not C++) ?

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

int main (int argc , char *argv[])
{
int i =0;
FILE *fp;
for (i=0 ; i< 10 ; i++)
{
fp = fopen (strcat("sample",i) , "wb");
fclose(fp);
}
}

ntubski 10-16-2006 07:13 AM

Quote:

char *strcat(char *dest, const char *src);

DESCRIPTION
The strcat() function appends the src string to the dest string over-
writing the `\0' character at the end of dest, and then adds a termi-
nating `\0' character. The strings may not overlap, and the dest
string must have enough space for the result.
strcat writes to the buffer pointed to by the first argument. Since you are putting a constant string, it is overwriting past the end, thus the segfault. You need to use a buffer with some space for writing extra letters:
Code:

int main (int argc , char *argv[])
{
int i =0;
FILE *fp;
char filename[16] = "sample";
  for (i=0 ; i< 10 ; i++)
  {
//strncat doesn't write more characters than the 3rd argument
      fp = fopen (strncat(filename,i, sizeof(filename)-6) , "wb");
      fclose(fp);
  }
}


tronayne 10-16-2006 07:14 AM

Try something like this instead:
Code:

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

int    main    (int argc, char *argv [])
{
        char    fname [FILENAME_MAX];
        int    i;
        FILE    *fp;

        for (i = 0; i < 10; i++) {
                (void) sprintf (fname, "sample%02d", i);
                if ((fp = fopen (fname, "w")) == (FILE *) NULL) {
                        (void) fprintf (stderr,
                            "%s:\tcan't open %s\n",
                            argv [0], fname);
                        exit (EXIT_FAILURE);
                }
                /*      close the input file            */
                if (fclose (fp)) {
                        (void) fprintf (stderr,
                            "%s:\tcan't close %s\n",
                            argv [0], fname);
                }
        }
        exit (EXIT_SUCCESS);
}


Wim Sturkenboom 10-16-2006 07:25 AM

And another problem that you will have is that i is an integer. You can not add an integer to a string, unless you use tronayne's solution above (sprintf).

mesh2005 10-16-2006 07:59 AM

Thank you all :)


All times are GMT -5. The time now is 12:25 PM.