OK .. so basically I have a program wich connects to an IRC server etc. .. and I'm trying to parse the IRC server's replys .. so I built a "parse_irc()" function wich should basicly split the server's reply into tokens separated by "\n" and pass each of these tokens to a "parse_line()" function to do the rest of the work ..
the parse_line() function is rather borring at the moment and looks something like this:
void parse_line(char* str)
{
fprintf(stdout, "parsing line: %s\n", str);
fflush(stdout);
return;
}
the parse_irc() function looks like this:
Code:
void parse_irc()
{
char *tok, *tokcpy, *auxbuf;
size_t unparsed_len;
unsigned char last_tok_is_unparsed = 0;
unparsed_len = strlen(unparsed);
if (unparsed_len > 0) {
auxbuf = malloc(unparsed_len+strlen(buf)-1);
if (auxbuf == NULL) {
perror("malloc");
exit(1);
}
strcpy(auxbuf, unparsed);
strcat(auxbuf, buf);
}
else {
auxbuf = malloc(strlen(buf));
if (auxbuf == NULL) {
perror("malloc");
exit(1);
}
strcpy(auxbuf, buf);
}
if (auxbuf[strlen(auxbuf)-1] != 10)
last_tok_is_unparsed = 1;
tok = strtok(auxbuf, "\n");
do {
tokcpy = tok;
tok = strtok(NULL, "\n");
if (tok != NULL)
parse_line(tokcpy);
} while (tok != NULL);
if (last_tok_is_unparsed == 1) {
unparsed = malloc(sizeof(tokcpy));
if (unparsed == NULL)
exit(0);
strcpy(unparsed, tokcpy);
}
else {
parse_line(tokcpy);
free(unparsed);
}
free(auxbuf);
return;
}
.. sorry for the lack of comments .. basicly , the parse_irc function treats the global variable "buf" in wich I read the server's replys:
(in function main
Code:
do {
if (read(socket_d, buf, sizeof(buf)-1) == 0)
return 1;
parse_irc();
} while (1);
the problem is .. if I call parse_irc from anywhere in main() (and I presume this would happen regardless of the function I'd be calling it from) , the program simply exits right away (exit code 0) .. if I , lets say , replace "parse_irc()" in main with "printf("%s", buf)", the program behaves normally and just prints the server's replys ..
oh .. and here are the definitions for "unparsed" and "buf" (global):
Code:
char nickname[10], buf[257], *unparsed;
does anyone know why this is happening ?
thanks!