Odd SEGFAULT Problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aviraldg
    New Member
    • Sep 2007
    • 21

    #1

    Odd SEGFAULT Problem

    I'm having a SEGFAULT on the following program. Weird thing is that it happens randomly with different "str"s (ie. user input; check main() for more info) and my debugger shows me that the getToken function is working and returning the correct answer.

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    char* getToken(char *src, unsigned int pos=0)
    {
    	char *token=new char[strlen(src)];
    	unsigned int i=0;
    	while(!isblank(src[pos]))
    	{
    		token[i]=src[pos];
    		pos++;
    		i++;
    	}
    	token[pos]='\0';
    	return token;
    }
    
    int main(int argc,char* argv[])
    {
    	puts("Enter command:");
    	char *str;
    	str=gets(str);
    	char *nstr=getToken(str);
    	puts(nstr);
    	return 0;
    }
    Note: The getToken(...) function is supposed to function like strtok , returning tokens.
    eg.
    Call: getToken("This a sample for testing this function"); (Currently works)
    Return: "This"

    Call: getToken("Anoth er sample",8); (Currently works)
    Return: "sample"

    Call: getToken("avira ldg aviraldg"); (SEGFAULTs)
    Returns: n/a
    Expected return: "aviraldg"

    Also, please note that this is not homework , and I'm trying to build a simple "some" script(ing language) parser here...
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Your 'str' variable doesn't point to a valid char buffer in your main() function.

    kind regards,

    Jos

    Comment

    • newb16
      Contributor
      • Jul 2008
      • 687

      #3
      And ( just in case ) in token function you should allocate strlen(str)+1 bytes to have place for trailing \0 if the string consists of one token.

      Comment

      Working...