Solved

Freeing memory (Malloc and free)

Posted on 2004-09-28
8
833 Views
Last Modified: 2010-04-15
Temp and temp1 are allocated in that order.
When i free temp, the memory is still being allocated (according to the OS's process manager)
But if i free temp1 as well, all the memory will be freed as desired, why is this so?
Pls advice

Using gcc version 3.2 20020903 (Red Hat Linux 8.0 3.2-7)

  float **Temp;
  if ((Temp = (float **)malloc (sizeof(float *)*row ))==NULL)
  {
      printf("Malloc failed (Unrecoverable)\n");
      exit(EXIT_FAILURE);
  }
  else
  {
      for (i=0; i<row; i++)
      {
          if ((Temp[i]=(float *)malloc(sizeof(float)*col))==NULL)
          {
              printf("Malloc failed (Unrecoverable)\n");
              exit(EXIT_FAILURE);
          }
      }
  }

printf("X: created 1\n");
  getchar();

  float **Temp1;
  if ((Temp1 = (float **)malloc (sizeof(float *)*row ))==NULL)
  {
      printf("Malloc failed (Unrecoverable)\n");
      exit(EXIT_FAILURE);
  }
  else
  {
      for (i=0; i<row; i++)
      {
          if ((Temp1[i]=(float *)malloc(sizeof(float)*col))==NULL)
          {
              printf("Malloc failed (Unrecoverable)\n");
              exit(EXIT_FAILURE);
          }
      }
  }
printf("X: created 2\n");
  getchar();
 
    for(i=0;i<row;i++)
    {
        free(Temp[i]);
    }

    free(Temp);
printf("X: freed 1\n");
  getchar();




0
Comment
Question by:jax79sg
8 Comments
 
LVL 11

Expert Comment

by:cjjclifford
Comment Utility
you should have a look at calloc() for allocating arrays of chunks of memory...

$ man calloc
     void *
     calloc(size_t count, size_t size);

DESCRIPTION

     The calloc() function contiguously allocates enough space for count
     objects that are size bytes of memory each and returns a pointer to the
     allocated memory.  The allocated memory is filled with bytes of value
     zero.  calloc() returns a NULL pointer if there is an error.


Also, if exiting on a failure of malloc(), it might be good to perror() rather than just printf(), or even better, do an abort() - generate a core dump for analysis later...
0
 
LVL 12

Expert Comment

by:stefan73
Comment Utility
Hi jax79sg,
Have a look at the sbrk() function. It is the base of process memory management. The man page explains how

When you first allocate temp and temp1, then free temp, you create a "gap" in the used memory. The data segment of a process must be contiguous, so its size can only be decreased after you've freed temp1, too.

Cheers!

Stefan
0
 
LVL 16

Accepted Solution

by:
PaulCaswell earned 20 total points
Comment Utility
Many C implementations make use of their own memory allocation schemes. When you allocate some memory using malloc, often the library will allocate a block much larger than the size you requested. Later allocation requests will slowly fill up this large block until it is full, at which time another large block will be allocated. These large blocks will only be freed when none of the memory they contain is in use any more.

In your case, allocation of temp1 created a large block, big enough to take bothe blocks. temp2 was also place in the block. You therefore only saw this block being freed after both had been deallocated.

Paul
0
 
LVL 45

Expert Comment

by:Kdo
Comment Utility
Hi jax79sg,

Paul's correct in his assessment.  Memory allocation occurs at several levels, and your program only deals with what it knows.  Everything else is transparent.

The reasons for the extra levels of buffering/assignment vary, but there are good reasons.  One is threading, where your program has multiple threads (pseudo-tasks) running simultaneously in the same address space.  There's a lot of potential overhead to be absorbed if every call to a memory management function has to lock memory so that it can change pointers without being stepped on by other threads.  Or worse, if memory management was always pushed to the "primary" thread so that the interlocks were handled by the fact that only one thread is making the updates.

But this all becomes much more efficient if each thread is allocated memory in blocks and the threads are free to plunder the blocks that they've been assigned.  The only time that there is an interlock issue is the assignment and freeing of these megablocks.


This is probably more information than you want right now, but one day it WILL make a difference to you!
Kent
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 7

Author Comment

by:jax79sg
Comment Utility
Paul, my program is iterative and makes use of free and malloc frequently. The result is that my program requirement on memory is always increasing (Since the real memmory is not freed till all are freed), till a stage where both my physical mem and paged mem runs out and the program crashes.

If malloc posed such a problem, is there any ways to get around this?
0
 
LVL 16

Expert Comment

by:PaulCaswell
Comment Utility
The only way to get around this is to free some memory. At first sight that doesnt sound too helpful but read on.

Obviously, if there is memory you dont need anymore free it, but I can imagine that as your problem or you would have worked out the answer yourself.

The second option is to page some memory out to disk. There is likely to be a number of blocks of memory that are only accessed in a few places. If you encapsulate these blocks in an object and only access the memory via a get/release mechanism then the object could intelligently write the memory block to disk and free it. This is like a paged memory system.

Paul

0
 
LVL 45

Expert Comment

by:Kdo
Comment Utility

If you're crashing a 32-bit program because of memory requests, you've got a huge problem.  You'll have requested and retained about 2GB.

I suspect that the crash lies elsewhere.  Perhaps you free() a block and use the pointer again before assigning a new block?

Have you considered realloc() to change a buffer size instead of free() and malloc()?


Kent
0
 
LVL 16

Expert Comment

by:PaulCaswell
Comment Utility
If you want to hunt down memory leaks you need to use the _Crt... functions such as _CrtSetAllocHook etc.

If this is nearer what you are looking for, let me know. I'll post some sample code.

Paul
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now