How to Free All Memory ?
Its possible, or only for to all position and clean one by one ?
How to Free All Memory ?
Its possible, or only for to all position and clean one by one ?
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; }
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
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.
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.
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.
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:
in this function, i send a CC (CheckConnection at each 30 s)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; }
when i receive some of CC
the program crash and send a message indicate alloc not sucessfull.
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.
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.
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
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.
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.
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.