Click to See Complete Forum and Search --> : Memory questions


Energon
04-28-2001, 09:41 PM
I'm doing some messing around with strings... filling buffers with various things, etc... so I have something like this:


char buf[256];

memset((void*)buf, 0, strlen(buf));
sprintf(buf, "my name\n");
printf("%s", buf);

memset((void*)buf, 0, strlen(buf));
sprintf(buf, "this is not longer my name\n");
printf("%s", buf);


and after that second sprintf, the memory is still all 0s... do I need to, instead work with dynamic allocation instead of static? Since in what I'm working on is using the same buffer for a send() and a recv() call and I'm trying to 0 out the memory before I bring in the next buffer so in case it's smaller, it doesn't keep the old junk in there... it's just not quite working right...

I'm also having some problems with using strlen() in the size of the buffer to 0 out (it's overwriting memory it shouldn't be in the stack) if I use the Debug version in Windows (it's code that runs in both Linux and Windows)... does MSVC do something different in the debug version with memory allocation that causes this kind of problem?

Stuka
04-29-2001, 04:00 PM
One thing that might be causing your problem is that strlen() expects a null terminated string - and of course there's no guarantee of that in a data buffer. You might use a symbolic constant BUF_SIZE where appropriate to ensure zeroing the whole thing...and does sprintf() put a '\0' on the end of the string? Again, if it doesn't, printf() will have problems. And yes, the Debug version of programs under MSVC will do some automatic memory initialization that could be causing your problems.

jemfinch
04-29-2001, 10:45 PM
strlen(3) only counts until the first '\0'. You should be using sizeof() in the cases where you're now using strlen(3).

Jeremy

Energon
04-30-2001, 01:44 AM
if I'm using a char* instead of an array, will I need to use a different method than sizeof() (since it should only return the pointer size, not the memory allocation size)...

jemfinch
04-30-2001, 09:42 AM
Originally posted by Energon:
if I'm using a char* instead of an array, will I need to use a different method than sizeof() (since it should only return the pointer size, not the memory allocation size)...

Probably. But from your sample, you're not using a char *, you're using an array.

Jeremy

Energon
04-30-2001, 02:09 PM
right, I just wanna make sure that in case I need it later, I'll know which to use...