Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip white space and return one word at a time in C

Tags:

c

string

pointers

This code is supposed to skip white space and return one word at a time. A couple of questions on this code: When the code gets to the *word++=c; line I get a core dump. Have I written this line correctly? and is return correct. And Do I need to somehow allocate memory to store the word?

//get_word

int get_word(char *word,int lim){
int i=0;
int c;   
int quotes=0;
int inword = 1;

while(
       inword &&
       (i < (lim-1)) &&
       ((c=getchar()) != EOF) 
      ){

  if(c==('\"')){//this is so i can get a "string"  
    if (quotes) {
      inword = 0;
    }
    quotes = ! quotes;
  }
  else if(quotes){ //if in a string keep storing til the end of the string
    *word++=c;//pointer word gets c and increments the pointer 
    i++; 
  }
  else if(!isspace(c)) {//if not in string store
    *word++=c;
    i++;
  } 
  else {
    // Only end if we have read some character ...
    if (i) 
      inword = 0;
  }
}
*word='\0';                            //null at the end to signify
return i;                               //value

}

like image 399
pisfire Avatar asked Nov 06 '22 07:11

pisfire


1 Answers

It's impossible to tell why this core dumps without seeing the code that calls get_word. The failure at the line you named implies that you are passing it something invalid in the first parameter. There's nothing wrong with that line in and of itself, but if word does not point to writable memory large enough to hold your output characters, you are in trouble.

The answer to your question about allocating memory to hold it is yes - however this could be local (e.g. a char array in the caller's local variables, global, or heap-based (e.g. from char * wordHolder = malloc(wordLimit);). The fact you are asking this supports the guess that your parameter 1 value is the problem.

like image 70
Steve Townsend Avatar answered Nov 09 '22 17:11

Steve Townsend