简体   繁体   中英

segmentation fault with c program

The program is getting input from a text file and then parsing them by space and then storing them in an array. I'm using the "<" in linux to read in the file.I needed to create a dynamically allocated array to store the words

if the input strings are "I am the cat in the hat" then the array should look like: index:

   "I" "am" "the" "cat" "in" "the" "hat" 
    0    1    2     3     4    5     6

I am getting a segmentation fault and I can't figure out why I am getting the error? I need to Any help would be appreciated.

code:

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

int main()
{

int wordCount = 1, i;
char ch,* wordsArray;

while((ch = getc(stdin)) != EOF)
    {
      if(ch == ' ') {++wordCount;}
    }

    wordsArray =(char*)malloc(wordCount * sizeof(char));

    for(i = 0; i<wordCount; i++)
     {
        scanf("%s",&wordsArray[i]);
        printf("%s\n", wordsArray[i])
     }
  return 0;
}

Edit: I have posted the actual code. I am no longer getting segmentation falls, but the words are not going in the array.

example output:

 a.out<dict.txt
(null)
(null)
(null)
(null)
(null)
(null)
(null)

Briefly, you're asking scanf to scan strings into memory space that you've only allocated big enough for a few integers. Observe that your malloc call is given a number of ints to allocate and then you're assigning that to a char * . Those two things don't mix, and what's happening is you're scanning a bunch of bytes into your buffer that is too small, running off the end, and stomping on something else, then crashing. The compiler is letting you get away with this because both malloc and scanf are designed to work with various types ( void* ), so the compiler doesn't know to enforce the type consistency in this case.

If your goal is to save the word tokens from the input string into an array of words, you can do that but you need to allocate something quite different up front and manage it a bit differently.

But if your goal is simply to produce the output you want, there are actually simpler ways of doing it, like with using strtok or just looping through the input char by char and tracking where you hit spaces, etc.

What you're trying to accomplish is parsing standard input. Some functions are available to assist you, such as strtok() and strsep() .

You will need an input buffer, which you can mallocate or use an array (I would use an array). As the functions parse the input string, you can fling off the words' addresses into a char pointer array. You could also build a linked list.

Finally, you must buffer input, which adds some delicious complexity to the operation. Still, it's nothing a good C programmer can't handle. Have fun.

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