Thread: How to Free All Memory ?

  1. #1
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184

    How to Free All Memory ?

    How to Free All Memory ?

    Its possible, or only for to all position and clean one by one ?

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Yes it's possible, just keep track of the memory you allocate*... Otherwise no it's not, at least not in the portable sense.

    * For example:
    Code:
    void * my_malloc(size_t n)
    {
       void * ptr = malloc(n);
    
       if(ptr)
       {
          /* add ptr to an array or linked list or something */
       }
    
       return ptr;
    }

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    It is possible for program to use its own memory management routine...

    At the start-up program allocates some big regeon using malloc (or something)
    Later - it uses only parts of this regeon by calling some home-made alloc/free procedures...

    When work is done - the whole regeon is freed - guarantiing that all the memory is returned to the OS
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    If you meant if there is a function to free all memory you've allocated so far, then no, there isn't.
    There are solutions as vart and zacs7 point out, but they do have their own overhead.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Registered User bboozzoo's Avatar
    Join Date
    Jan 2009
    Posts
    14
    Well it's not so hard actually, as long as you know what you're doing and don't care about screwing up libc allocator (never tested it though, but I do not see any reason why it should not).
    On UNIX you have brk/sbrk call. Calling sbrk with 0 as argument will give you the pointer to the current heap (top/bottom? depending on arch supposedly). So at the start of the program call sbrk(0), then later at some point call sbrk(0) again, calculate the difference and call sbrk(difference).

    Anyway, although it's possible, I'd never do it that way in real application.

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by bboozzoo View Post
    Well it's not so hard actually, as long as you know what you're doing and don't care about screwing up libc allocator (never tested it though, but I do not see any reason why it should not).
    On UNIX you have brk/sbrk call. Calling sbrk with 0 as argument will give you the pointer to the current heap (top/bottom? depending on arch supposedly). So at the start of the program call sbrk(0), then later at some point call sbrk(0) again, calculate the difference and call sbrk(difference).

    Anyway, although it's possible, I'd never do it that way in real application.
    That is an almost guaranteed way to crash your system... But yes, that would do the task sergioms is asking for - but not a good idea to do that.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    To answer the full question in simple terms: No you can't.

    A longer answer is:
    Assuming there was a way to say "free everything allocated from the heap", you would potentially cause all sorts of problems. Say for example you use "fopen()" to open a file, and you later on call the "magicalfreeeverythingfunction()" - what happens if you call fread() on your file, and the fopen() called malloc to get its internal buffer? If it doesn't go wrong at that point, it almost certainly WILL go wrong when that memory gets allocated for a different reason, because fread() will overwrite the data in the memory you just allocated.

    And whilst sergioms's code may not use fopen, fread, etc, it certainly does use library functions that we do not know exactly what the underlying code does. Functions that allocate and free memory arbitrarily are not required to identify themselves in any particular way. So any attempt to free "all memory" without knowing what it represents is almost certain to cause problems.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    My Equipment is crazy
    I think it not free memory when I Try.

    Because, im all alloc and de-alloc, but sometimes it crash.

    Example:

    Code:
    int VcomCmdUser(TCPREADDATA *p)  	// Processa as Entradas Recebidas Pelo Usuário. (Obj. Comunicação
    { 	
    	unsigned int iSckMaxBuffer = 128;
    	
    	if (p->Length >= 4 && p->Length <= iSckMaxBuffer){	// Pelo Menos 4 Caracteres [STX]XX[13][10]
    		ProcessaChamado (p->ReadUartChar, p->Length);
    		ClearStr (p->ReadUartChar);
    	}	
    	return 1;  
    }
    
    int ProcessaChamado (unsigned char *pPacote, int pLen){
    	
    	unsigned char *cFuncao;
    	unsigned char *cSubFuncao;
    	unsigned char *cPacote;
    	
    	int iPosStart, iPosEnd, iPosTam;
    	
    	cPacote = malloc (pLen);
    	if (cPacote == NULL)
    		VcomSendSocket(iUserSocket, "3-ERRO DE ALOCAÇÃO DE MEMÓRIA", 29);	
    	else
    		//VcomSendSocket(iUserSocket, pPacote, pLen);	
    	
    	//Separa o Pacote
    	iPosStart = strpos (pPacote, cSTX);
    
    	iPosStart++;
    	
    	iPosEnd = strpos (pPacote, cCR);
    	
    	iPosTam = iPosEnd - iPosStart;
    		
    	if((iPosStart >= 0) && (iPosEnd)){
    		substring(&pPacote[iPosStart], cPacote, iPosTam);
    	
    		if(strlen (cPacote) > 0){
    						
    			substring(&cPacote[0], cFuncao, 2);
    			
    			if (strcmp (cFuncao, "OP") == 0){								// Recebe Ordem de Pesagem
    				substring(&cPacote[3], cSubFuncao, iPosTam - 2);
    				OrdemProducao (cSubFuncao);
    			}
    			else if (strcmp (cFuncao, "OI") == 0){							// Recebe Ordem de Pesagem Item
    				substring(&cPacote[2], cSubFuncao, iPosTam - 2);
    				OrdemProducaoItem (cSubFuncao);
    			}
    			else if (strcmp (cFuncao, "OK") == 0){							// Tratamento de Confirmações
    				substring(&cPacote[2], cSubFuncao, 2);
    				if (strcmp (cSubFuncao, "OP") == 0)	{						// Recebe Confirmação de Ordem de Pesagem
    					EnviaPedidoPC ("OISL", 4);		
    				}
    				else if (strcmp (cSubFuncao, "OI") == 0){					// Recebe Confirmação de Ordem de Pesagem Item
    					//if (iItemID == 1){
    					lPesoTara = lPeso;
    					iPesaItem = 1;
    				}
    				else if (strcmp (cSubFuncao, "IR") == 0){					// Recebe Confirmação de Entrega de Resposta de Item 
    					EnviaPedidoPC ("OISL", 4);
    				}
    			}
    			else if (strcmp (cFuncao, "FI") == 0){							// Recebe Finaliza Item Indicando que Recebeu Todos Itens da OP
    					iStepInput0 = 0;
    					iItemID = 0;
    					iPesaItem = 0;
    					EnviaPedidoPC ("OPFI", 4);
    					EscreveDisplay ("ORDEM CONCLUIDA.........................", 3);
    			}
    			else if (strcmp (cFuncao, "ER") == 0){							// Erro do Objeto de Comunicação
    				iStepInput0 = 0;
    				substring(&cPacote[3], cSubFuncao, iPosTam - 3);
    				EscreveDisplay (cSubFuncao, 3);
    			}
    			else if (strcmp (cFuncao, "CC") == 0){							// Check Connection
    				// CheckConnection, Não faz nada.
    			}
    			else{
    				// Pacote Não Identitificado;
    			}
    		} 
    		else { 
    			free (cPacote);
    			return 0;
    		}
    	}
    	
    	free (cPacote);
    	
    	return 1;
    }
    in this function, i send a CC (CheckConnection at each 30 s)
    when i receive some of CC
    the program crash and send a message indicate alloc not sucessfull.

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    That indicates memory corruption - which a "free all" function would not solve.
    Get a debugger and start debugging!
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Nov 2008
    Location
    Santa Catarina - Brasil
    Posts
    184
    Quote Originally Posted by Elysia View Post
    That indicates memory corruption - which a "free all" function would not solve.
    Get a debugger and start debugging!

    I love debug,

    but this not a pc
    is a icp-i7188E3

    and, use a Serial RS-232 to communicate with a balance
    a serial 485 to send text to a led display
    socket to communicate with a listen socket software
    and Digital I/O

    when the program crash
    it closed all outputs, and no send a message about the error.

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I think I've pointed out twice (if not three times) that you are not allocating memory for cFuncao and cSubFuncao [variable names from memory] - you also do not really NEED to use allocation here, fixed size arrays should work perfectly fine.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Well the only way to free all memory is to call exit() (or return from main()...), but I'm guessing you don't actually want to free everything...
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  13. #13
    Banned
    Join Date
    Jan 2009
    Posts
    30
    If by free everything, one only needs to free all handles currently owned by the current process or a certain target process, I do not believe that the question is quite as dangerous nor far-fetched as many have made it sound. Perhaps with a little further explanation as to what purpose this would serve may help us better point you in the right direction.

    My gut feeling is that you keep running into issues where your program is eating away a great deal of system resources and your solution is to go ahead and deallocate everything. Thus eliminating the leaked memory handles. If this is the case, you probably should find out why you are leaking so much memory. If not, then if you are doing this in the event that malloc() returns NULL and wish to "free all" to hopefully claim memory resources for your own I would say this is an ill-advised application programming strategy. Considering the fact that your user may have important tasks eating up all the memory you can never assume too much about why the user is out of RAM.

    -sphynxster.

  14. #14
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Yes, freeing all KNOWN pointers is fine - however, that doesn't actually solve the problem of a memory leak that I'm pretty sure is what sergioms was actually referring to - however, I also think that this is not ACTUALLY the problem in this case - it is a case of abusing memory allocated (or constant data strings) elsewhere.

    Also, to "close all known handles" requires that you know what those are.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  15. #15
    Banned
    Join Date
    Jan 2009
    Posts
    30
    Very true, some mallocs keep a full table of handles internally though. So its reasonable to say that with a keen enough understanding of the internal data structures used you could theoretically free a handle without knowing what it was. At this point we are no longer talking OS specific, we are talking a specific libc or a specific kernel build. It would be an implimentation so specific it would hardly be worth investigating if the initial issue is indeed a mishandled memory leak. I can only leave it up to sergioms to point us in the direction of what he was trying to do.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with shared memory shmdt() shmctl()
    By Jcarroll in forum C Programming
    Replies: 1
    Last Post: 03-17-2009, 10:48 PM
  2. Replies: 7
    Last Post: 02-06-2009, 12:27 PM
  3. Memory leak with detached pthreads - how to free?
    By rfk in forum Linux Programming
    Replies: 2
    Last Post: 08-17-2007, 06:50 AM
  4. free memory in structure
    By franziss in forum C++ Programming
    Replies: 22
    Last Post: 01-08-2007, 05:16 PM
  5. free allocated memory on interrupts
    By scrappy in forum C Programming
    Replies: 4
    Last Post: 02-20-2004, 11:13 AM