Segmentation violation ...

From: lijowski@cosray2.wustl.edu
Date: Thu Jan 21 1999 - 21:55:58 MET


  The following code crashes most of the time with the 
  segmentation violation in root 2.20/06 for SunOS5.4 on Sparc.
  But when compiled with gcc it works fine. It works also 
  when instead calling a function I parse a string inside
  main macro.

  Thanks for any hints.
 
   Regards

   Michal Lijowski

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

// -------------------------------------------------------------------------

 int  getfloats(char *tmpstr, float *aa)
// extracts up to 10 floating point numbers from a string

 {
   int  SLEN = 40;
   char  cc[2], str1[SLEN];

   int  sl = strlen(tmpstr);
   printf("%4d  %s", sl, tmpstr);
   cc[0] = tmpstr[0];
   int jj = 0;
   int ii = 0;
   while ( (ii < 10) && (jj < sl) ) {
       str1[0] = '\0';
       while ( (cc[0] != ' ') && (jj < sl) ) {
           strncat(str1, cc, 1);
           jj++;
           cc[0] = tmpstr[jj];
       } 
       aa[ii] = atof(str1);
       ii++;
  // skip white spaces
       while ( (cc[0] == ' ') && (jj < sl) ) {
           jj++;
           cc[0] = tmpstr[jj];
       }
   }
   return ii;
 }

// ---------------------------------------------------------------------

void  test_read()
{
   char infile[200];
   float aa[10];
   int  SLEN = 80, nn;
   char  tmpstr[SLEN], str1[20], cc[2];

      sprintf(infile, "tmp.dat");
      printf("%s\n", infile);
      FILE *infp = fopen(infile, "r");
      if  (infp == NULL) {
         printf("test_read2b can't open %s\n", infile);
         exit(1);
      }
      int npts = 0;
// loop until EOF
      while (fgets(tmpstr, SLEN, infp) != NULL) {
         printf(" %s", tmpstr);
         nn = getfloats(tmpstr, aa);
         for (int  ii = 0; ii < nn; ii++) {
            printf(" %f  ", aa[ii]);
         }
         printf("\n");
         npts++;
      }
      fclose(infp);
 }

 A few lines of numbers from tmp.dat file.
0 318.52
1 318.51
2 318.51
3 318.50
4 318.50
5 318.49
6 318.48
7 318.47
8 318.46
9 318.45



This archive was generated by hypermail 2b29 : Tue Jan 04 2000 - 00:43:28 MET