Re: memory allocation problems
- From: "Steve Long" <Steve_Noneya@xxxxxxxxxx>
- Date: Tue, 31 May 2005 15:17:39 -0700
Victor,
Thanks for your reply. Here's the entire body of the function. I don't seem
to be able to get (nothrow) to work. I've include <new>:
void WriteMessage(FILE* fp, const char* msg)
{
time_t curr = time(0);
char* curtime = ctime((const time_t*) &curr);
char* buffer = new char[(strlen(curtime) + strlen(msg) + 3)];
strcpy(buffer, curtime);
strcat(buffer, msg);
strcat(buffer, "\n\n");
if (fp != NULL)
fwrite(buffer, 1, strlen(buffer), fp);
free(curtime);
delete[] buffer;
return;
}
"Victor Bazarov" <v.Abazarov@xxxxxxxxxxxx> wrote in message
news:%23%23%23TfRiZFHA.580@xxxxxxxxxxxxxxxxxxxxxxx
> Steve Long wrote:
> > this is probably most fundamental but I don't code in C++ often and I'm
just
> > not getting why the code is crashing with a:
> > Unhandled exception at 0x77f75a58 in FileIOTest.exe: User breakpoint
> >
> > I have a function that calls this line of code:
> >
> > char* buffer = new char[sizeof(char) * (strlen(curtime) + strlen(msg) +
3)];
>
> OK, sizeof(char) is always 1, you can easily drop it. Now, what is
> 'curtime'? Is it something that can be passed to 'strlen'? What is
> 'msg'? Same question, can it be passed to 'strlen'? Remember that
> 'strlen' is very fragile, it has undefined behaviour if you pass NULL
> to it...
>
> > The first time I call the function, all is well but subsequent times it
> > crashes with the above exception. All I'm doing is a strcpy, strcat and
> > writing to a file in the funciton and then I delete buffer memory using
> > delete.
> >
> > What could the problem be. Sorry is this is just really stupid...
>
> Could be that you're just running out of memory... Try
>
> char* buffer = new (nothrow) char[strlen(curtime)
> + strlen(msg) + 3];
>
> and see if NULL is returned.
>
> V
.
- Follow-Ups:
- Re: memory allocation problems
- From: Alexander Grigoriev
- Re: memory allocation problems
- From: Simon Trew
- Re: memory allocation problems
- From: Emil Kvarnhammar
- Re: memory allocation problems
- Prev by Date: Re: How to search binary occurences in files
- Next by Date: Re: memory allocation problems
- Previous by thread: Re: memory allocation problems
- Next by thread: Re: memory allocation problems
- Index(es):
Relevant Pages
|