Skip to main content
gamedev.net
🔒 Locked

Simple stuff

Started by Briskon Jul 23, 2003 at 10:32 AM 3 replies 250+ views
Original Post
Briskon
Briskon
Two simple questions........... 1. When you use the strdup() function do you have to free memory afterwards? 2. What''s the advantages/differences of using "char *theString" as opposed to "char theString[30]". Thanks
nickwinters
nickwinters
I know nothing about your first question.

But for the second question, if you use an array, there''s a maximum length. If you use the pointer, there is no maximum length. You just need to make sure you don''t overwrite stuff in memory.
KurtCPP
KurtCPP
I think the advantage of ysing a pointer instead of an array is that you can dynamically ad libitum (ie as often as you want) resize it using memory functions so that its never too wide nor too small. Thus, you can adapt its size to user''s needs.

Regarding the function of your first quest., I dont even know what it is. Sorry about it.

Hope it helps.


Prog, Hex & Rock''n''Roll :
I don''t like the Prog but the Prog likes me.
Some nice poetry to sweeten your spirit and relax a bit before programming
Prog, Games & Rock'n'Roll :I don't like the Prog but the Prog likes me.
jhavna
jhavna
yes, strdup allocates memory for you, which must be freed when your string is no longer needed.

The advantage is that you don''t waste memory or overflow it. Say you have a piece of code that accepts a bit of text at runtime. you don''t know how long that text is at this point. So if you use char* text you can dynamically allocate enough memory for the length of the string, whereas with the static allocation (char string[30]) you cannot have more than 29 chars (+ null char) otherwise the buffer will overflow.

on the other hand, if you make char string[x] really big, you will probably be wasting memory, as you will not use all of the array, unless you know that any string passed to it will be around X chars.

personally to avoid memory leaks i would use char[X] if you know that the string will be quite close to X (ie. a few chars shorter) and never bigger! if the string can be anything, use char* string.

-----------------------
"Without a sense of humour we couldn''t react to a lot of things"
-----------------------"Without a sense of humour we couldn't react to a lot of things"
Briskon
Briskon
Thanks, that''s what I wanted to know.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.