看板 DFBSD_bugs 關於我們 聯絡資訊
Adrian Nida wrote: >>That's what I thought, but I thought when you called free() it didn't >>actually touch the data there, just mark it as free for other programs >>to use or something? > > > You're right; free doesn't touch the data at that memory location. So the > best case would be your data is still accessible. However, you should never > expect this to be the case. > > >>So.. it's actually pretty impossible for me to free tmp_cp anyway in >>this case isn't it? The function seems to return cp as an integer, so I >>can't free tmp_cp if I need cp pointing, so be able to prepend(?) /dev/ >>into the string? > > > It is possible to free tmp_cp, but it isn't going to give you the intended > effect. If you were doing a "deep copy" (creating a place in memory for cp > and then copying the value of each item from tmp_cp to its respective place > in cp) you should free tmp_cp. However, because you are just telling cp to > point to the same location as tmp_cp you have to remember that that area of > memory is still needed. That makes sense, thanks :) In that case though it looks to be impossible for me to free the memory as the pointer gets returned, as already mentioned. > > Now, the fact that you are returning cp as an integer when it is really a > char* raises a flag with me. I would return the pointer, and then have the > calling function free the memory location (unless that function hands the > memory location off to something else). However, I haven't seen the entire > code path so I don't know the intention and can't comment if this idea fits > into its view. It's not me who's returning it :) I just noticed that it was being returned as an int at the end of the function. Here's a snippet of the end: --- signal(SIGALRM, SIG_DFL); return ((int)cp); } (void)uu_unlock(uucplock); } signal(SIGALRM, f); return (deadfl ? -1 : (int)cp); } --- The original cp is delcared as: register char *cp; and I have tmp_cp as: char *tmp_cp; Originally I tacked it onto the end of the register one, but made my own as just char * as I don't know what register does. It should be alright shouldn't it? > > Self memory managing can be tricky, but if you keep to these guidelines > you'll be better off: > > * malloc/new only when you need it (Some OSes single-thread malloc which > cripples MP performance) > * Never assume malloc/new return what you need > * Do whatever you like to that memory location > * free the pointer when you no longer need it > * Never access that memory location again unless you are told to by malloc I think I will write those down :) Well, copy and paste to file more like! > > Adrian > -- Internet Explorer? Try FireFox at http://www.mozilla.org/products/firefox/ Outlook Express? Try ThunderBird at http://www.mozilla.org/products/thunderbird/