473,386 Members | 1,823 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

How to reuse the dynamically allocated memory inside a function in main()?

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4.  
  5.  
  6.  
  7. int **transpose(int **x,int m,int n);
  8.  
  9.  
  10.  
  11. main()
  12. {
  13.   int nrows=2,ncolumns=2,i,j,k=0;
  14.  
  15.  
  16.   //memory allocation for array x
  17.   int **array;
  18.   array = malloc(nrows * sizeof(int *));
  19.   if(array == NULL)
  20.     {
  21.       printf("out of memory\n");
  22.       return 0;
  23.     }
  24.  
  25.  
  26.   for(i = 0; i < nrows; i++)
  27.     {
  28.       array[i] = malloc(ncolumns * sizeof(int));
  29.       if(array[i] == NULL)
  30.     {
  31.       printf("out of memory\n");
  32.       return 0;
  33.     }
  34.     }
  35.  
  36.  
  37.  
  38.  
  39.  
  40.  
  41.   //define x
  42.   printf("x=\n");
  43.   for(i=0;i<2;i++)
  44.     {
  45. printf("\n");      
  46.   for(j=0;j<2;j++)        
  47.     {
  48.       k=k+5;
  49.       array[i][j]=i+j+k;
  50.       printf("%d\t",array[i][j]);
  51.     } 
  52.     }
  53.   printf("\n");
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.   //memory allocation for x_transpose, (storing the transpose returned by function)
  61.  
  62.   int **x_transpose;
  63.   x_transpose = malloc(nrows * sizeof(int *));
  64.   if(x_transpose == NULL)
  65.     {
  66.       printf("out of memory\n");
  67.       return 0;
  68.     }
  69.  
  70.  
  71.   for(i = 0; i < nrows; i++)
  72.     {
  73.       x_transpose[i] = malloc(ncolumns * sizeof(int));
  74.       if(x_transpose[i] == NULL)
  75.     {
  76.       printf("out of memory\n");
  77.       return 0;
  78.     }
  79.     }
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.   //call function
  88.   x_transpose= transpose(array,nrows,ncolumns);
  89.  
  90.  
  91.  
  92.  
  93.  
  94.  
  95.   //display transpose
  96.   printf("x_transpose=\n");
  97.   for(i=0;i<2;i++)
  98.     {
  99. printf("\n");      
  100.   for(j=0;j<2;j++)        
  101.     {
  102.       printf("%d\t",x_transpose[i][j]);
  103.     }
  104.     }
  105. }
  106.  
  107.  
  108.  
  109.  
  110.  
  111.  
  112.  
  113.  
  114.  
  115. //function_transpose
  116.  
  117. int **transpose(int **x,int m,int n)
  118. {
  119.   int nrows=n,ncolumns=m,i,j;
  120.  
  121.   //memory allocation for y,to store transpose
  122.   int **y;
  123.   y = malloc(nrows * sizeof(int *));
  124.   if(y == NULL)
  125.     {
  126.       printf("out of memory\n");
  127.       return 0;
  128.     }
  129.   for(i = 0; i < nrows; i++)
  130.     {
  131.       y[i] = malloc(ncolumns * sizeof(int));
  132.       if(y[i] == NULL)
  133.     {
  134.       printf("out of memory\n");
  135.       return 0;
  136.     }      
  137.     }
  138.  
  139.  
  140.  
  141.  
  142.  
  143.   for(i=0;i<m;i++)
  144.     for(j=0;j<n;j++)
  145.       {
  146.     y[i][j]=x[j][i];
  147.       }
  148.   return y;
  149. }
  150.  
i allocated memory for storing y(transpose of matrix) inside the function. also i allocated memory(for x_transpose) for storing the same result in main program. can reuse the same memory in main also???
Jan 15 '11 #1

✓ answered by weaknessforcats

Answer to question 1:
Yes. That's correct. The only additional thing I would do is set the pointer to 0. By convention any non-zero pointer is assumed to contain a valid address. 0 is widely recognized as "no address inside", that is, a null pointer.

Answer to question 2:
When you use malloc, you receve a pointer to the memory allocated by malloc. If you lose that pointer you lose your allocation:

Expand|Select|Wrap|Line Numbers
  1. void Func()
  2. {
  3.  
  4.    int* ptr = malloc(sizeof(int) * 20);
  5. }
When Func() returns ptr is deleted. The allocated memory is still there and it is still yours. Only now there is no way to access it. That allocation will stay there until the program completes and it permanently reduces the amount of free memory available. Hence this is called a memory leak--the free memory just drains away.

You must either return ptr or you must free the allocation while still inside Func().

Answer to question 3:
You free memory when your program no longer will access it. That may be inside the function or it may be in
main(). One of the problems in freeing allocated memory is knowing when to do it. There are some techniques that would take too much room to go into here. I suggest additional reading or Googleing.

4 3484
weaknessforcats
9,208 Expert Mod 8TB
YOu have what appears to be serious memory issues.

This code:

Expand|Select|Wrap|Line Numbers
  1.  int **x_transpose; 
  2.   x_transpose = malloc(nrows * sizeof(int *)); 
  3.  etc...  
  4.  
  5.    //call function 
  6.   x_transpose= transpose(array,nrows,ncolumns); 

It appears the address allocation of x_transpose is overwritten by the transpose function.

Also your allocated memory is never freed.

As far reuse goes any allocated memory is your to use as often as you wish until you free it. The real trick is keeping all of the addresses of your allocations in scope. If you lose an address you lose the allocation.
Jan 16 '11 #2
1.thanks.. that helps. so i need not have to allocate memory for x_transpose, and just need to declare as
Expand|Select|Wrap|Line Numbers
  1. int **x_transpose
????
2. i am afraid i did not get the sentence,
"As far reuse goes any allocated memory is your to use as often as you wish until you free it. The real trick is keeping all of the addresses of your allocations in scope. If you lose an address you lose the allocation. "
3. where should i free the memory allocated inside a function? is it at the end of the function or at the end of main program???
Jan 16 '11 #3
weaknessforcats
9,208 Expert Mod 8TB
Answer to question 1:
Yes. That's correct. The only additional thing I would do is set the pointer to 0. By convention any non-zero pointer is assumed to contain a valid address. 0 is widely recognized as "no address inside", that is, a null pointer.

Answer to question 2:
When you use malloc, you receve a pointer to the memory allocated by malloc. If you lose that pointer you lose your allocation:

Expand|Select|Wrap|Line Numbers
  1. void Func()
  2. {
  3.  
  4.    int* ptr = malloc(sizeof(int) * 20);
  5. }
When Func() returns ptr is deleted. The allocated memory is still there and it is still yours. Only now there is no way to access it. That allocation will stay there until the program completes and it permanently reduces the amount of free memory available. Hence this is called a memory leak--the free memory just drains away.

You must either return ptr or you must free the allocation while still inside Func().

Answer to question 3:
You free memory when your program no longer will access it. That may be inside the function or it may be in
main(). One of the problems in freeing allocated memory is knowing when to do it. There are some techniques that would take too much room to go into here. I suggest additional reading or Googleing.
Jan 17 '11 #4
ok. got it.. thanks..
Jan 18 '11 #5

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

Similar topics

2
by: Ralph Krausse | last post by:
How can I dynamically allocate memory in VB? I wish to do this.... Dim szData as String * 250 I can't allocate memory like this cause I am not sure how much to alloate. I want to do...
5
by: csnerd | last post by:
I have a really simple question. What is the difference between allocating memory following way: #1 int main(int argc,char* argv) { char str)+1]; return 0; }
3
by: Tony Johansson | last post by:
Hello Experts!! When you instansiate varaibles(object) you can do so in four different scops which are. Within a block which is called Local or block scope . Within a function which is called...
1
by: kapilk | last post by:
I have a pointer to which has been allocated some memory now how do i find out the number of Bytes allocated? Thanks
1
by: akywy | last post by:
Two questions about the following code sample: --- code begins --- //class IPv4 is defined elsewhere list<IPv4> ip_list; for (int i=1; i<=9; i++) { char addr; ...
3
by: Jinkuzo | last post by:
Have been working on this project for a week, unfortunately missed the lesson on it and have been struggling to figure it out. These are the instructions and the point at which I'm up to. ...
15
by: tom | last post by:
why delete the dynamically allocated memory twice causes an error, see the code below: int _tmain(int argc, _TCHAR* argv) { int *pi = new int(12); cout<<*pi; delete pi; delete pi; }
2
by: sdkumar00 | last post by:
How can we avoid/detect multiple free calls for a dynamically allocated memory. void example() { int *a; a = (int *)malloc(10); free(a); free(a); //how can we detect/avoid multiple...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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...

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.