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.
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...
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;
}
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...
Comment