Dynamic Allocation

Started by
4 comments, last by Blue*Omega 23 years, 3 months ago
If you have a string you want to read in but don''t know it''s size, only that it ends in a 0, and waant to store it to [char String1;] is there any way to just add one byte to the current char list? I mean like: String1 += (char*) malloc(sizeof(char)); I know this doesn''t work, I''ve tried it. Is there a way? ----------------------------- Blue*Omega (Insert Witty Quote Here)
// Tojiart
Advertisement
You''ll have to (not have to, but this is the easier way) find out how big it is first, then you can store it.

Or, you can read it is chunk (say, of 10 bytes), and use 2 dynamicly allocated arrays, and swap as needed to make the other bigger.

Or create a linked list style string class.


http://www.gdarchive.net/druidgames/
The way I do this is to allocate a buffer that you think will NEVER get filled i.e. 512 chars or something.

Read the string into that buffer...
find the length of the string.
Allocate the new buffer.
And do a strcpy.

easy as pie



Regards,
Nekosion
Regards,Nekosion
Thanks for the help! Nekosion, could you please explain a bit more? I think I know what your saying but would like an example.

-----------------------------

Blue*Omega

(Insert Witty Quote Here)
// Tojiart
Use a temp string function as previously mentioned, (as long as you know your strings won''t go over a certain length). You have a temporary string buffer and call a function to get a pointer to a string of a certain size. The buffer is circular in nature so as you grab strings from it, it will eventually start over-writing itself. An obvious disadvantage if you need a whole pile of strings all at once.

#define MAX_TEMP_STRING_SPACE (512l)


char temp_string[MAX_TEMP_STRING_SPACE];
int temp_string_free = 0;


char *TempString( int size )
{
char *p;

if ( size > MAX_TEMP_STRING_SPACE ) ... error!!!!!!!
if ( MAX_TEMP_STRING_SPACE - temp_string_free < size ) temp_string_free = 0;

p = &temp_string[temp_string_free];
temp_string_free += size;

return p;
}



There''s really nothing wrong with:

char *new_string;

new_string = (char*)malloc( strlen(old_string) + 1 );
strcpy( new_string, old_string );

Apart from memory fragmentation... but that''s a different story ;-)


---Strange

---Strange
quote:Original post by Nekosion

The way I do this is to allocate a buffer that you think will NEVER get filled i.e. 512 chars or something.


Just be carefull.
One guy wrote OpenGL info viewer ("GLview", as I remember)
But when I tried it on Quadro with latest driver - CRASH!
I''ve found the reason after some debugging - he had a "buffer that he thought will NEVER get filled" - char [1024].
String with OpenGL extensions list for Quadro was ~1100 characters...

This topic is closed to new replies.

Advertisement