Re: Access violation in free()
- From: Tor Rustad <tor_rustad@xxxxxxxxxxx>
- Date: Sun, 02 Sep 2007 18:11:31 +0200
Richard Heathfield wrote:
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);
I consider this better:
assert(NULL != s);
before calling strlen().
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);
}
Unless you are writing e.g. a non-stop server (or a library for it, kernel mode code etc.), the normally best thing to do on memory failures, is simply to exit.
Propagating NULL all over the place, result in bloated and hard-to-read code.
--
Tor <torust [at] online [dot] no>
.
- Follow-Ups:
- Re: Access violation in free()
- From: Martin Ambuhl
- Re: Access violation in free()
- From: Richard Heathfield
- Re: Access violation in free()
- From: Richard
- Re: Access violation in free()
- References:
- Access violation in free()
- From: spl
- Re: Access violation in free()
- From: Martin Ambuhl
- Re: Access violation in free()
- From: Richard Heathfield
- Access violation in free()
- Prev by Date: Re: size_t problems
- Next by Date: Re: Writing portable code...
- Previous by thread: Re: Access violation in free()
- Next by thread: Re: Access violation in free()
- Index(es):