473,657 Members | 2,463 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

10 New Member
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
4 3515
weaknessforcats
9,208 Recognized Expert Moderator Expert
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
vineesh vs
10 New Member
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 Recognized Expert Moderator Expert
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
vineesh vs
10 New Member
ok. got it.. thanks..
Jan 18 '11 #5

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

Similar topics

2
2672
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 something like this.. dim iLen as Integer dim szData as String
5
2366
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
3607
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 function scope. Whithin a class which is called class scope. Outside a function which is called global or file scope. Now to my question when you allocate memory dynamically you can't say
1
1228
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
1711
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; sprintf(addr, "%d.%d.%d.%d", i,i,i,i);
3
2553
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. So essentially we don't know the size of the array and the user doesn't specify size, it's all done on the fly. Point I'm up to:
15
1780
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
2404
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 free calls }
0
8411
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8323
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8739
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7351
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6176
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5638
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1732
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.