473,597 Members | 2,459 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

About Memory Allocation and function calls

My situation is here:

an array of two dimension can only be defined locally within a
function(becaus e the caller don't know the exact size ). Then the
question is: how should the caller access this array for future use?

The code is:
*************** *******
caller()
{
...
function();

other code also wish to access the array elements in function, how
should I do?
}

function()
{
calculation I want to encapsulate within this function....... ..
...
got the size: 'num_of_row' and 'num_of_col'
char maze[num_of_row][num_of_col];
...
code to fill the array

return;
}

I consider to use malloc() to allocate memory for this array, and
return the pointer to this run time allocated memory back to the
caller, however, another question arise: can the caller possibly
access this local memory(got from malloc())? because I think it's
still only belong to the function being called----rules of scope
suppose to work.

Can any one explain the memory allocation when compiling (in stack)
and at run time (heap)?
And what kind of rules are on top of these two different kinds of
resources? Which should C programmer should pay attention to?

I am kind of lost into these concepts when I debug my program:-)

Best

Ji

Mar 21 '07 #1
3 1863
On Mar 21, 7:45 pm, "william" <william.m...@g mail.comwrote:
My situation is here:

an array of two dimension can only be defined locally within a
function(becaus e the caller don't know the exact size ). Then the
question is: how should the caller access this array for future use?
<snip>
I consider to use malloc() to allocate memory for this array, and
return the pointer to this run time allocated memory back to the
caller, however, another question arise: can the caller possibly
access this local memory(got from malloc())?
Yes, of course.
because I think it's
still only belong to the function being called----rules of scope
suppose to work.
Just pass the pointer malloc() gives you back to the caller.

Mar 21 '07 #2
Fr************@ googlemail.com wrote:
>
On Mar 21, 7:45 pm, "william" <william.m...@g mail.comwrote:
My situation is here:

an array of two dimension can only be defined locally within a
function(becaus e the caller don't know the exact size ). Then the
question is: how should the caller access this array for future use?

<snip>
I consider to use malloc() to allocate memory for this array, and
return the pointer to this run time allocated memory back to the
caller, however, another question arise: can the caller possibly
access this local memory(got from malloc())?

Yes, of course.
because I think it's
still only belong to the function being called----rules of scope
suppose to work.

Just pass the pointer malloc() gives you back to the caller.
/* BEGIN maze.c */

#include<stdio. h>
#include<stdlib .h>

char **caller(int num_of_row, int num_of_col);
char **function(int num_of_row, int num_of_col);

int main(void)
{
char **maze;
int index = 3;
int index2 = 5;

maze = caller(index, index2);
if (maze != NULL) {
while (index-- != 0) {
free(maze[index]);
}
free(maze);
}
return 0;
}

char **caller(int num_of_row, int num_of_col)
{
char **maze;
int index, index2;

maze = function(num_of _row, num_of_col);
if (maze != NULL) {
for (index = 0; index != num_of_row; ++index) {
for (index2 = 0; index2 != num_of_col; ++index2) {
printf("maze[%d][%d] is %d\n",
index, index2, maze[index][index2]);
}
}
}
return maze;
}

char **function(int num_of_row, int num_of_col)
{
char **maze;
int index, index2;

maze = malloc(num_of_r ow * sizeof *maze);
if (maze == NULL) {
return NULL;
}
for (index = 0; index != num_of_row; ++index) {
maze[index] = malloc(num_of_c ol * sizeof *maze[index]);
if (maze[index] == NULL) {
while (index-- != 0) {
free(maze[index]);
}
free(maze);
return NULL;
}
}
for (index = 0; index != num_of_row; ++index) {
for (index2 = 0; index2 != num_of_col; ++index2) {
maze[index][index2] = (char)(index + index2);
}
}
return maze;
}

/* END maze.c */

--
pete
Mar 21 '07 #3
On 21 Mar 2007 12:45:39 -0700, "william" <wi**********@g mail.com>
wrote:
>My situation is here:

an array of two dimension can only be defined locally within a
function(becau se the caller don't know the exact size ). Then the
question is: how should the caller access this array for future use?

The code is:
************** ********
caller()
{
...
function();

other code also wish to access the array elements in function, how
should I do?
}

function()
{
calculation I want to encapsulate within this function....... ..
...
got the size: 'num_of_row' and 'num_of_col'
char maze[num_of_row][num_of_col];
...
code to fill the array

return;
}

I consider to use malloc() to allocate memory for this array, and
return the pointer to this run time allocated memory back to the
caller, however, another question arise: can the caller possibly
access this local memory(got from malloc())? because I think it's
still only belong to the function being called----rules of scope
suppose to work.

Can any one explain the memory allocation when compiling (in stack)
and at run time (heap)?
And what kind of rules are on top of these two different kinds of
resources? Which should C programmer should pay attention to?

I am kind of lost into these concepts when I debug my program:-)
Allocated memory remains allocated until it is explicitly freed. In
order for the calling function to know the address of the allocated
memory, the called function must make it available. There are several
techniques to make it available. Two popular ones are: it can be
returned with a return statement and it can be stored in a variable
the calling function has access to (such as a global variable).

In addition to the address of the allocated memory, the calling
function also needs to know the number of dimensions (always two in
your example) and the size of each.

Now that we know the called function must make three values available
to the calling function, return seems like a poor choice. However, if
the calling function passes some object addresses to the called
function, the called function can store the appropriate values in
those objects. Consider the following stripped down code just to
illustrate the technique.

int called_function (char **ptr_to_ptr, size_t *dim1, size_t *dim2){
*ptr_to_ptr = malloc(total_si ze_of_array);
*dim1 = size_of_first_d imension;
*dim2 = size_of_second_ dimension;
return some_status_val ue;
}

int main(void){ /* calling function */
char *array;
size_t first_dimension ;
size_t second_dimensio n;
inst status;
status = called_function (&array, &first_dimensio n,
&second_dimensi on);
/* If status indicates success, use the array. To access element
[i][j] use the expression array[i*first_dimensi on+second_dimen sion].
*/
Remove del for email
Mar 24 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

72
3574
by: ravi | last post by:
I have a situation where i want to free the memory pointed by a pointer, only if it is not freed already. Is there a way to know whether the memory is freed or not?
18
2432
by: Peter Smithson | last post by:
Hi, I've read this page - http://devrsrc1.external.hp.com/STK/impacts/i634.html but don't understand it. Here's the text - "Non-standard usage of setjmp() and longjmp() could result in compatibility problems. The contents of the jmp_buf buffer are specific
50
2819
by: Joseph Casey | last post by:
Greetings. I have read that the mistake of calling free(some_ptr) twice on malloc(some_data) can cause program malfunction. Why is this? With thanks. Joseph Casey.
16
2311
by: Pedro Graca | last post by:
I have a file with different ways to write numbers ---- 8< (cut) -------- 0: zero, zilch,, nada, ,,,, empty , void, oh 1: one 7: seven 2: two, too ---- >8 -------------- I wanted to read that file and put it into dynamic memory, like
74
4636
by: ballpointpenthief | last post by:
If I have malloc()'ed a pointer and want to read from it as if it were an array, I need to know that I won't be reading past the last index. If this is a pointer to a pointer, a common technique seems to be setting a NULL pointer to the end of the list, and here we know that the allocated memory has been exhausted. All good. When this is a pointer to another type, say int, I could have a variable that records how much memory is being...
1
1455
by: kiplring | last post by:
List<string> effectList = new List<string>(); effectList.Clear(); effectList = null; using (List<string> effectList = new List<string>()) { } If there are so many calls, I should save as much memory as I can.
94
4683
by: smnoff | last post by:
I have searched the internet for malloc and dynamic malloc; however, I still don't know or readily see what is general way to allocate memory to char * variable that I want to assign the substring that I found inside of a string. Any ideas?
4
3698
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and value-initialization. I think default-init calls default constructor for class objects and sets garbage values to PODs. Value-init also calls default constructor for class objects and sets 0s to POD types. This is what I've learned from the books (especially...
14
3820
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
0
7893
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
8276
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8259
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
5847
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
5436
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
3889
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
3932
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2408
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1243
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.