简体   繁体   中英

Storing a char in an array segfault

I'm getting a segfault in my code and I'm not sure why. I read through a file and count the number of lines in order to dynamically allocate my arrays. I then rewind the file, read the data in the file, storing the data into variables, and then storing the read variables into arrays, but I'm having trouble with chars.

   ...
   char *aname = malloc(sizeof(char) * 3); 
   ... 
   // get # lines in file (count)
   ... 
   char *aname_seen = malloc(count * (sizeof(char) * 3));
   ...
   rewind(file);
   while (fgets(buff, sizeof buff, file) != NULL) 
   {
      if (sscanf(buff, "%s %d %s %s %d %lf %lf %lf %lf %lf\n", 
         atm, &serial, aname, resName, &resSeq, &x, &y, &z, 
         &occupancy, &tempFactor) == 10)
      {
         aname_seen[i] = *aname;
         printf("%d: %s vs %s\n", i, aname, aname_seen[i]);

         i++;

      } // end sscanf if-loop

   } // end while loop

I can print aname with printf("%d: %s\\n", i, aname) and get the expected output, but I'm getting Segmentation fault (core dumped) when I try printf("%d: %s vs %s\\n", i, aname, aname_seen[i]) .

This while loop + nested if loop is the same convention I use to count the number of lines, so i will increment up to count. Am I incorrectly allocating aname_seen and not actually giving it count number of char*3 elements? I'm not well versed in messing with char's. More of a numerical fortran buff, so I need some direction.

Thanks in advance!

The %s format specifier is supposed to correspond to a char * argument. In your case, aname_seen[i] is a char , which gets promoted to an int for the purpose of passing to a variadic function ( printf ). An int is not a char * .

Perhaps you meant one of these:

printf("%d: %s vs %c\n", i, aname, aname_seen[i]);
printf("%d: %s vs %s\n", i, aname, &aname_seen[i]);

If neither of these solve your problem, please explain precisely the behaviour you expect from this expression and give us a minimal, compilable testcase. Your current testcase isn't compilable.

you way you defined aname_seen is a pointer to a char array

char *aname_seen = malloc(count * (sizeof(char) * 3));

so aname_seen[i] is a char

so the

printf("%d: %s vs %s\n", i, aname, aname_seen[i]);

should be

printf("%d: %s vs %c\n", i, aname, aname_seen[i]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM