views:

103

answers:

1

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

}

+2  A: 

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.

Steve Townsend
Would you mind if I remove the cast from the return value of `malloc`?
R..
@R.., without this I get a compile error since `malloc` returns `void*`: error C2440: 'initializing' : cannot convert from 'void *' to 'char *' Conversion from 'void*' to pointer to non-'void' requires an explicit cast"
Steve Townsend
@Steve: Then you are probably using a C++ compiler to compile C code :)
FredOverflow
Yes that's right. Interestingly the MSDN CRT docs for `malloc` say this cast is needed: "To return a pointer to a type other than void, use a type cast on the return value."
Steve Townsend
@Steve: You're reading C++ documentation and using a C++ compiler, not a C compiler. Since this is a homework assignment and you tagged it C, I'm going to assume you were supposed to be writing C. Switch to a C compiler. C and C++ are not remotely the same language.
R..
@R.. - I was not sure about this and checked my standard reference (MSDN since I am MS-centric) for the CRT, which are wrong, or at best insufficiently clear that the text applies to C++ compilation of CRT usage. I'll do the suggested edit, anyway - thanks.
Steve Townsend