Re: Access violation in free()



Martin Ambuhl said:

<snip>
Try the following and see if you have better luck:
<snip>

char *CopyString(char *s)

Better: char *CopyString(const char *s)

{
int length = strlen(s);

Better: size_t length = strlen(s);

char *t = malloc(length+1); /* note! */
strcpy(t, s); /* in your original code, this violated the bounds
of
the array pointed to by t, corrupting memory. */

Better: before copying to the newly created buffer, ensure it exists:

if(t != NULL)
{
strcpy(t, s);
}

or even:
if(t != NULL)
{
memcpy(t, s, length + 1);
}

since you already have that information to hand.

return t;
}

#if 0
void main()
#endif
int main(void)
{
char *destStr;
char *sourceStr = "Test";
destStr = CopyString(sourceStr);
printf("Destination String : %s\n", destStr);

Again, check that destStr is not a null pointer before passing it to
printf.

<snip>

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
.



Relevant Pages