Welcome to the Builder Academy

Question Bug found in get_number (strcpy overlapping strings)

More
16 Oct 2013 08:43 #4425 by Ornir
Hi everyone,

We have been experiencing some REALLY random, strange bugs. We have an enter command, for entering portals, and if you type enter 2.pool for example, it would come back: There is no plol here.

Here is what the man page for strcpy says:
Code:
The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns! (See BUGS.)

I looked into this, and our function get_number, which is the exact same as stock, was corrupting the string! It was using memcpy and copying two overlapping strings, see the code below:
Code:
int get_number(char **name) { int i; char *ppos; char number[MAX_INPUT_LENGTH]; *number = '\0'; if ((ppos = strchr(*name, '.')) != NULL) { *ppos++ = '\0'; strlcpy(number, *name, sizeof(number)); strcpy(*name, ppos); /* strcpy: OK (always smaller) */ (HERE! ppos is a pointer to a position in *name!) for (i = 0; *(number + i); i++) if (!isdigit(*(number + i))) return (0); return (atoi(number)); } return (1); }

Here is my solution - It may not be the most efficient way to do it but it works and I believe that it is safe. Basically, copy the string within the function, process, copy to the original string and then free the copy.
Code:
int get_number(char **name) { int i, retval; char *ppos, *namebuf; char number[MAX_INPUT_LENGTH]; *number = '\0'; retval = 1; /* Default is '1' */ /* Make a working copy of name */ namebuf = strdup(*name); if ((ppos = strchr(namebuf, '.')) != NULL) { *ppos++ = '\0'; strlcpy(number, namebuf, sizeof (number)); strcpy(*name, ppos); /* strcpy: OK (always smaller) */ for (i = 0; *(number + i); i++) if (!isdigit(*(number + i))) retval = 0; retval = atoi(number); } free(namebuf); return retval; }

I hope this was useful.

- Ripley/Ornir Elunari
Head Coder, Luminari MUD

Luminari - a Pathfinder/D&D inspired adventure!
www.luminarimud.com
luminarimud.com 4100
The following user(s) said Thank You: thomas

Please Log in or Create an account to join the conversation.

Time to create page: 0.178 seconds