0

I have been thinking in this for a while but I'm not sure if it's "safe" and possible.

Imagine something like this:

void genLeaks(void)
{
 char* charLeakAddr;
 charLeakAddr = (char*)malloc(sizeof(char) * 10);
 strcpy(charLeakAddr, "Hello World");
}

As I understand this will create a memory leak because charLeakAddr is not released ( free (charLeakAddr); ).

Now in main :

int main(void)
{
 genLeaks();

 ??????? 

 return 0;
}

In the place marked with ??????? is there a way to create some kind of function that frees the memory allocated by charLeakAddr?

Thanks for your time.

Sorry but, how can I do to make the code good looking in the post :S ?

Thanks for your answers.

Somehow I produced this code and it seems to work ( I tested it in GCC with Code::Blocks in both Linux and Windows) Please take a look at it. Is it correct? or it is just crazy to try something like it?

#include <malloc.h>
#include <stdio.h>
#include <string.h>

#define LEAKS_PATH_FILE               "leaks.txt"
#define WIN_ERASE_LEAKS_FILE_COMMAND  "erase leaks.txt"
#define UNIX_ERASE_LEAKS_FILE_COMMAND "rm leaks.txt"

#define __ASM__LEAK__DELETER__DEBUG

#define __UNIX__DEBUG__

unsigned int LEAKS = 0;

void regLeakAddr(void* memPtr, const char* fileName)
{
 FILE* arch;

 #ifdef __ASM__LEAK__DELETER__DEBUG
  printf("\nMemory Leak : 0x%x\n", (void*)memPtr);
 #endif

 arch = fopen(fileName, "a");

 if(arch)
 {
  fprintf(arch, "%d", (void*)memPtr);
  fprintf(arch, "%c", '\n');
  fclose(arch);
  LEAKS++;
 }
 else
  printf("ERROR IN FILE leaks.txt\n");
}

void assemblyDeleter(int numAddr)
{
 #ifdef __ASM__LEAK__DELETER__DEBUG
  printf("\nOnassemblyDeleter : 0x%x\n\n", numAddr);

  #ifdef __UNIX__DEBUG__
   getchar();
  #else
   system("pause");
  #endif
 #endif

 char* deleter;
 int*  ptr = &numAddr;

 printf("\n======> 0x%x\n\n", *ptr);
 printf("\n======> 0x%x\n\n", deleter);

 if((char*)*ptr > deleter)
 {
  printf("(ptr > deleter) : Offset : 0x%x\n", ((char*)*ptr - deleter));
  deleter += ((char*)*ptr - deleter);
 }
 else
 {
  printf("(ptr < deleter) : Offset : 0x%x\n", (deleter - (char*)*ptr));
  deleter += ((char*)*ptr - deleter);
 }

 printf("deleter =========> 0x%x\n", deleter);

 #ifdef __ASM__LEAK__DELETER__DEBUG
  puts(deleter);
 #endif

 free(deleter);

 #ifdef __ASM__LEAK__DELETER__DEBUG
  puts(deleter);
 #endif

 deleter = NULL;
 ptr     = NULL;
}

void freeMemory(void)
{
 if(LEAKS == 0)
 {
  #ifdef __ASM__LEAK__DELETER__DEBUG
   printf("NO LEAKS\n");
  #endif
  return;
 }

 FILE* arch;
 int   addr;
 int i;

 arch = fopen(LEAKS_PATH_FILE, "r");

 if(arch == NULL)
 {
  #ifdef __ASM__LEAK__DELETER__DEBUG
   printf("Error on file...\n");
  #endif
  return;
 }

 for(i = 0; i<LEAKS; i++)
 {
  fscanf(arch, "%d", &addr);
  assemblyDeleter(addr);
 }

 fclose(arch);

 #ifdef __UNIX__DEBUG__
  system(UNIX_ERASE_LEAKS_FILE_COMMAND); 
 #else
  system(WIN_ERASE_LEAKS_FILE_COMMAND); 
 #endif
}

void genLeakTrick(char** msg)
{
 *msg = (char*)malloc(sizeof(char) * 17);
 strcpy(*msg, "Hello World again");
 printf("\n%s\n", *msg);
}

void genLeaks(void)
{
 char* charLeakAddr;
 charLeakAddr = (char*)malloc(sizeof(char) * 10);
 strcpy(charLeakAddr, "Hello World");
 printf("\n%s\n", charLeakAddr);
 //free(charLeakAddr);
 regLeakAddr(charLeakAddr, LEAKS_PATH_FILE);

 char* charLeakAddr2;
 genLeakTrick(&charLeakAddr2);
 //free(charLeakAddr2);
 regLeakAddr(charLeakAddr2, LEAKS_PATH_FILE);
}

int main(void)
{
 genLeaks();

 freeMemory();

 return 0;
}
5
  • There's a bright ? on the upper-right corner of the editors on this site. Click on it for formatting help next time ;-)
    – Mat
    Mar 15, 2011 at 19:13
  • Select the code, then click on the {} button on the toolbar. For more information, take a look at the Editing Help page (you can get to it by clicking on the orange "?" on the toolbar).
    – ZoogieZork
    Mar 15, 2011 at 19:14
  • Note that you're allocating 10 bytes and then copying 12 bytes into it. Even ignoring the leaks, you're overwriting memory. Mar 15, 2011 at 19:36
  • The code you found is extremely ugly and wrong at least in the fact that it's using reserved symbol names (beginning with _ followed by another _ or capital letter) which results in undefined behavior. Mar 15, 2011 at 19:43
  • Also, -1 for lying. "Somehow I produced this code" - no, you copied and pasted it from somewhere. Mar 15, 2011 at 19:47

3 Answers 3

1

No, there is no way to free that memory. It's permanently lost (unless you can somehow find the pointer that was originally returned by malloc).

You can always just free it in genLeak since it's not being used for anything after that. If you return the pointer though, someone else is going to have to free it after it's used.

That's why in C library documentation whenever a pointer is returned, they tell you who the pointer is owned by and if you have to free it or not.

3
  • Jonathan that's exactly what I thought but some how I produced this code that apparently works. Please take a look at it:
    – LEH
    Mar 15, 2011 at 19:23
  • 2
    What do you mean "works"? Code with a memory leak will still work, it just won't ever free the memory. This isn't a problem if the process dies because the OS will reclaim the memory itself. If it's a long running application, this can leave you starved for memory if it allocates enough and doesn't free the memory it isn't using anymore. To see if your program has memory leaks, I suggest a program called valgrind. Mar 15, 2011 at 20:01
  • 1
    @EMT: The code you "produced" does not meet the requirements. You changed the genLeaks function so that it does store the allocated address. Note that the way it stores it (using a file) is extremely bad. If the file is modified to contain the wrong information, it could cause your program to invoke undefined behavior leading to severe bugs. Mar 15, 2011 at 20:02
0

No way, until the genleak() return type is void. Modifying the return type and if the function returns a reference of charLeakAddr, it would be possible.

char* genleak()
{
    char* charLeakAddr;
    charLeakAddr = (char*)malloc(sizeof(char) * 10);
    strcpy(charLeakAddr, "Hello World");

    return charLeakAddr ;
}

int main()
{
     genleak(); // Now also not possible, since the return value is not collected.
     char* temp = genleak();

     free temp;  // Deallocating the resources acquired using malloc
     return 0;
}

Edit:

In the posted snippet, charLeakAddr goes out of scope up on return of function call genleak(). Thus, making the resources stay there on the free way making no process to access the leaked sources. How about adding a global variable ?

char* globalVar = NULL ;
void genleak()
{
    char* charLeakAddr;
    charLeakAddr = (char*)malloc(sizeof(char) * 10);
    // ....
    globalVar = charLeakAddr ;
}

int main()
{
    // .....
    genleak();
    free globalVar ;
}

And in genleak(), assign the value of where charLeakAddr is pointing to it. And then, the program can perform a free operation on it.

6
  • The original example does not have a problem with scope, as you suggest in your edit. In the original example, the fact that charLeakAddr goes out of scope does not matter. By returning a char* you copied all the data that went out of scope. If you had returned a char** containing a char* pointer to char *charLeakAddr then you would have had a problem with scope.
    – Theo
    Mar 15, 2011 at 19:43
  • @Theo - When a reference is returned, data pointed by reference is not copied !!!
    – Mahesh
    Mar 15, 2011 at 19:52
  • @Mahesh: You need to consider where each piece is located. The pointer charLeakAddr is a stack variable. The memory that malloc() allocates is on the heap. When you exit the function the stack variable charLeakAddr is destroyed but the heap allocated space is not touched. You don't have to copy the pointed data because unless you call free() no one will destroy it.
    – Theo
    Mar 15, 2011 at 20:01
  • @Theo - I meant the same. I was quoting on your comment - " By returning a char* you copied all the data that went out of scope. "
    – Mahesh
    Mar 15, 2011 at 20:10
  • @Mahesh: Great, so then we both agree that there is no scope problem in your original example, and that the edited version which uses a global solves no problem at all.Moreover, using globals is not considered a good practice unless absolutely required. Which means that your edited example with globals is actually worse than your original example.
    – Theo
    Mar 15, 2011 at 20:26
-1

Yes, there's a way, that's called garbage collector. You can read this and this for some heads up. Basically if all your program is compiled/linked with the garbage collector, you might be able to do things like

gc.collect()

to claim back all leaked memory.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.