Re: Access violation in free()
- From: Richard Heathfield <rjh@xxxxxxxxxxxxxxx>
- Date: Sun, 02 Sep 2007 06:22:03 +0000
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
.
- Follow-Ups:
- Re: Access violation in free()
- From: Tor Rustad
- Re: Access violation in free()
- References:
- Access violation in free()
- From: spl
- Re: Access violation in free()
- From: Martin Ambuhl
- Access violation in free()
- Prev by Date: Re: size_t problems
- Next by Date: Re: size_t problems
- Previous by thread: Re: Access violation in free()
- Next by thread: Re: Access violation in free()
- Index(es):
Relevant Pages
|