473,563 Members | 2,895 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Secure Memory Allocation and Free

1,059 Top Contributor
Its always a trouble for me to securely freeing allocated memory. By Securely I mean free all the memory. So, I have developed a simple method that might help me to do so. I didnt use it in any project, but I will, anyway,
here is the two file:
secmem.h
Expand|Select|Wrap|Line Numbers
  1. #ifndef secmem_h
  2. #define secmem_h 1
  3. #include<stdlib.h>
  4. void * secureAlloc(size_t size,int Line, char *FileName);
  5. short secureFree(void *ptr);
  6. short freeAll();
  7. #endif
  8.  
  9.  
secmem.c
Expand|Select|Wrap|Line Numbers
  1. #include "secmem.h"
  2. #include <stdio.h>
  3. #include <string.h>
  4. struct MemoryList
  5. {
  6.     long MemoryAddress;
  7.     int line;
  8.     char fileName[20];
  9.     struct MemoryList *Next;
  10. };
  11. static struct MemoryList *Start,*Last;
  12.  
  13. void * secureAlloc(size_t size,int Line, char *FileName)
  14. {
  15.     long newAddress,newAddress2;
  16.     newAddress=(long)malloc(size);
  17.     newAddress2=(long)malloc(sizeof(struct MemoryList));
  18.     if(Start==NULL)
  19.     {
  20.         Start=(struct MemoryList *)newAddress2;
  21.         Last=Start;
  22.         Last->MemoryAddress=newAddress;
  23.         Last->line=Line;
  24.         strcpy(Last->fileName,FileName);
  25.     }
  26.     else
  27.     {
  28.         Last->Next=(struct MemoryList *)newAddress2;
  29.         Last=(struct MemoryList *)newAddress2;
  30.         Last->MemoryAddress=newAddress;
  31.         Last->line=Line;
  32.         strcpy(Last->fileName,FileName);
  33.     }
  34.     return (void *)newAddress;
  35. }
  36. short secureFree(void *ptr)
  37. {
  38.     struct MemoryList *Cont,*Prev;
  39.     long temp=(long)ptr;
  40.     if(ptr!=NULL)
  41.     {
  42.         free(ptr);
  43.     }
  44.     else
  45.     {
  46.         return 1;
  47.     }
  48.     Cont=Start;
  49.     Prev=Cont;
  50.     while(Cont)
  51.     {
  52.         if((long)Cont->MemoryAddress==temp)
  53.         {
  54.             if(Cont==Start)
  55.             {
  56.                 Start=Cont->Next;
  57.                 free(Cont);
  58.                 if(Start==NULL)
  59.                 {
  60.                     Last=NULL;
  61.                 }
  62.                 return 0;
  63.             }
  64.             else
  65.             {
  66.                 Prev->Next=Cont->Next;
  67.                 free(Cont);
  68.                 if(Prev->Next==NULL)
  69.                 {
  70.                     Last=Prev;
  71.                 }
  72.                 return 0;
  73.             }
  74.         }
  75.         else
  76.         {
  77.             Prev=Cont;
  78.             Cont=Cont->Next;
  79.         }
  80.     }
  81.     return 1;
  82. }
  83.  
  84. short freeAll()
  85. {
  86.     struct MemoryList *Cont,*Next;
  87.     int Count=0;
  88.     Cont=Start;
  89.     while(Cont)
  90.     {
  91.         Next=Cont->Next;
  92.         printf("File Name: %s, Line Number : %d\n",Cont->fileName,Cont->line);
  93.         free(Cont);
  94.         Cont=Next;
  95.         Count++;
  96.     }
  97.     printf("Total Freed : %d\n",Count);
  98. }
  99.  
Test file:
test.c

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include "secmem.h"
  3. struct test_
  4. {
  5.     char *a;
  6.     char *b;
  7.     char *c;
  8.     struct test_ *Next;
  9. }*test;
  10.  
  11. int main()
  12. {
  13.     test=secureAlloc(sizeof(struct test_),__LINE__,__FILE__);
  14.     test->a=(char*)secureAlloc(10,__LINE__,__FILE__);
  15.     secureFree(test);
  16.  
  17.     freeAll();
  18.     return 0;
  19. }
  20.  
  21.  

Now how it work,
in the test.c, I have called secureAlloc, including the line number and file name.

at the end of the program, I have called freeAll() function.
When It runs the free all function it also print all the line number and the file name from where the allocation has been requested.
This helps a lot in case of debugging and make sure all the allocated memory has been freed.

Final Steps, whenever you are sure enough that all memory has been freed then add some macro in common header file and remove the freeAll() function
test.h
Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. //#include "secmem.h"
  5. #define secureAlloc(a,b,c) malloc(a)
  6. #define secureFree(a) free(a)
  7.  
  8. struct test_
  9. {
  10.     char *a;
  11.     char *b;
  12.     char *c;
  13.     struct test_ *Next;
  14. }*test;
  15.  
  16. int main()
  17. {
  18.     test=secureAlloc(sizeof(struct test_),__LINE__,__FILE__);
  19.     test->a=(char*)secureAlloc(10,__LINE__,__FILE__);
  20.     secureFree(test);
  21.  
  22. //    freeAll();
  23.     return 0;
  24. }
  25.  
Hope, this will help
Oct 7 '11 #1
0 4213

Sign in to post your reply or Sign up for a free account.

Similar topics

6
3835
by: benevilent | last post by:
Hey, I'm trying to debug the memory allocation in an embedded use of the Python interpreter. The longer I leave my program running the more memory it consumes. The total number of objects in the system is not increasing (many are being allocated and deallocated). Using mtrace I have established that the only memory which is not being
2
2642
by: mosfets | last post by:
Hi, I'm having a little trouble figuring out the difference in terms of memory allocation between: class person_info; class A { private:
9
2768
by: Andrew Au | last post by:
Dear all, I am trying to write a piece of software that use Object Oriented design and implement it with C, I did the following == In Object.h == typedef struct ObjectStructure* Object; Object object_create(); int object_getIntegerAttribute(Object object);
66
3575
by: Johan Tibell | last post by:
I've written a piece of code that uses sockets a lot (I know that sockets aren't portable C, this is not a question about sockets per se). Much of my code ended up looking like this: if (function(socket, args) == -1) { perror("function"); exit(EXIT_FAILURE); } I feel that the ifs destroy the readability of my code. Would it be
17
2502
by: farshid | last post by:
I have written a long program with c, and am using dynamic memory allocation. This program is supposed to be run over and over (300 times) for a long simulation. But the program stops after 120 cycles due to memory leackage. I am not very expert in programing but it seems that my free() function does not do anything to my program. One example of...
24
19045
by: Ken | last post by:
In C programming, I want to know in what situations we should use static memory allocation instead of dynamic memory allocation. My understanding is that static memory allocation like using array is faster than malloc, but dynamic memory allocation is more flexible. Please comment... thanks.
1
7953
by: Peterwkc | last post by:
Hello all expert, i have two program which make me desperate bu after i have noticed the forum, my future is become brightness back. By the way, my problem is like this i the first program was compiled and run without any erros but the second program has a run time error when the function return from allocate and the ptr become NULL. How to...
7
2670
by: siddhu | last post by:
Dear experts, If I do free(p); memory pointed by p is freed and is available for further allocations in the process. But how does it decide about how much memory (size) has to to be freed and make it available for further allocations? Regards, Siddharth
14
3815
by: vivek | last post by:
i have some doubts on dynamic memory allocation and stacks and heaps where is the dynamic memory allocation used? in function calls there are some counters like "i" in the below function. Is this stored in stack. If yes whether it will be deleted on exiting from the function. is dynamic memory allocation needed for this purpose
1
2656
by: gianx80 | last post by:
Hi, I'm studying the basis of C, C++ and Assembly languages at my university (I have two exams about these subjects, for now) ... and I have a problem ^^. I wrote a program in C (not so optimized, this isn't our present goal for my professors) that recieves in input an integer (matrix size) and a double pointer to a square matrix and...
0
7583
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7888
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7642
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6255
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5484
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.