Game Development Community

Char buffer gets corrupted

by gamer · in Torque Game Engine · 01/10/2007 (6:49 pm) · 5 replies

In side a function I have:
char buf[256]
stream.readString(buf);
array.push_back(buf,buf);

I checked the array content and the buffer, it's valid when the function exits, but soon at some time later array content gets corrupted by some random junk data. to solve this problem I have to use StringHandle to pack the data into StringTable that torque provided.
so the code that works is:
const char* buf=con->unpackStringHandleU(stream).getString();
array.push_back(buf, buf);
this of course assumes that I used con->packStringHandleU() earlier to pack the string into the stream.

so a general question is:
is this a general behavior under torque's memory management or c++ in general? when I allocate a char buf[256] inside a function, and then add it to an array, after the function exists, this piece of string obviously is still referenced, why does torque allow other junk written to it??
what am I missing?

thanks!

#1
01/10/2007 (11:18 pm)
It's normal c++ scoping. When you declare a buf like that within a function, it's only valid within the function. When you leave the function, it goes out of scope and the memory is pushed back to the heap.
#2
01/11/2007 (12:11 am)
So what is the right way to allocate a buffer that stays? using new char[256]?
#3
01/11/2007 (1:26 am)
I think what you're missing is that the vector you're using probably does not store the buffer directly, but as a pointer which gets invalid (and points to some other piece of memory) as soon as the scope of that function is lost. This is the impression I get from Stephen's post.
#4
01/11/2007 (4:22 am)
If you want it to persist outside the function, you'll have to use new().
#5
01/11/2007 (5:24 pm)
Thanks all.
stefan, I believe that's what happend.