Hi I have a situation here in which i malloc a char_t* pt and free it. If I want to reuse this pt and malloc it of another size. Will there be any risk involved?
Hi I have a situation here in which i malloc a char_t* pt and free it. If I want to reuse this pt and malloc it of another size. Will there be any risk involved?
Yes, there is risk involved. The further apart the second malloc is from the first free, the higher the chance you might blunder (though setting the pointer to be a null pointer after the free may mitigate potential blunders). But if you talk about correctness rather than risk, then indeed it can be done correctly.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
One tactic you might explore to mitigate some of the risk is the creation of intermediate scopes in your programs...
This will let you create variables use them and forget about them on the fly.Code:// lots of code { <-- scope starts here char *pchar = malloc(100 * sizeof(char); // do stuff with pchar free(pchar); } <-- scope ends here pchar is destroyed // more code
Here's a live code example... (it's Windows API code, but I think you'll get the idea)
Code:void GoButton( void ) { WCHAR password[25]; { WORD port; GetWindowText(Wind[4],password,24); port = _wtoi(password); InitNetwork(port); } { DWORD pcode; WCHAR ltxt[MAX_LOGLINE]; GetWindowText(Wind[2],password,24); pcode = SetPassCode(password); if (!pcode) { lstrcpy(ltxt,L"Password improperly entered"); AddToLog(L"Error",ltxt); } } EnableWindow(Wind[2],0); EnableWindow(Wind[4],0); EnableWindow(Wind[5],0); }
Last edited by CommonTater; 08-21-2011 at 09:49 PM. Reason: Edited braces so nit pickers won't complain about my formatting style
Oh boy... sharp as a tack on C Code ... not so good with humour, I see...
It's an old engineering joke in faux latin... Iligitimi = Illigitimate = Child born out of wedlock. Carborundum is a brand name for grindstones. Non = negative, no, not...
Thus ... "Don't let the b**tards wear you down"
Last edited by CommonTater; 08-22-2011 at 10:05 AM.
If you can get around freeing the pointer, you could use realloc(), but check its returns for any pitfalls.
realloc