| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | Re: free() |
-=> Quoting Frank Adam to All <=-
Hi Frank,
FA> Could someone tell or show me how to free dynamically allocated
FA> memory in one function from another function or main ?
FA> eg:
FA> main()
FA> {
FA> foo();
FA> }
FA>
FA> char* foo()
FA> {
FA> char *s = malloc(80);
FA> }
FA> If this function is to return s, freeing it before return would
FA> not be a good idea, is that true ?
Very true. :)
FA> If it is, how would i then get access to s to free it ? It's
FA> out of scope, as silly as is i've tried free(s) from main,
FA> compiler says "what s?" of course. Btw, i have thought about
FA> freeing it before returning, and it *seems* to work fine in DOS,
FA> but i don't know how safe that is.
You should *NEVER* attempt to access memory that you have freed. :(
FA> I also believe that in a multitask environment, that would be
FA> fatal if another program got a slice between free() and return,
FA> am i thinking straight here or not ?
Sort of. :) Try something like this:
int main(void)
{
char *p;
/* ... */
p = foo();
/* ... */
free(p);
return 0;
}
char *foo()
{
char *s = malloc(80);
/* ... */
return s;
}
Do you see what's going on?
Michael Stapleton of Graphic Bits.
* AmyBW v2.10 *
... In C, the solution probably has to do with asterisks or something.
--- AmyBW v2.10
* Origin: The Three Amigas - better than two (3:713/615)SEEN-BY: 50/99 620/243 623/630 711/401 409 410 413 430 808 809 932 934 SEEN-BY: 712/508 515 713/111 317 601 611 615 618 700 826 888 914 714/906 SEEN-BY: 800/1 @PATH: 713/615 888 711/808 934 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.