473,395 Members | 1,624 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,395 software developers and data experts.

memory versus variable scope

Hello folks,

I have three interrelated questions. I'm sorry if these are newbie questions, but I can't seem to find these answers in online searches.

- can one declare several pointers in main(), pass these pointers as arguments to a function, point these pointers to malloc'd memory inside this function, and still access this memory in main() after the function returns? An initial experiment suggested that this is illegal, which I interpret to mean that declaration of a pointer and the memory allocated to that pointer each have individual scopes and that the scope of the allocated memory does not inherit the scope of the pointer.

- can one define a pointer to an array "above main", then allocate the memory for it in a function that is called from within main() and still have the memory be accessible to main after the function returns? I suspect based on what I interpreted from the above experiment that the answer is no.

- If a pointer to an array is declared above main and malloc'd at the top of main, is the memory assigned to the array visible within all functions that are called later from within main?

Many thanks,
kris
Jan 27 '09 #1
8 1941
So some example programs I just wrote suggest that answers to my questions are NO, YES, and YES. If I am wrong and my example programs failed to show a memory violation, please let me know.

Thanks for looking,
kris
Jan 27 '09 #2
newb16
687 512MB
In the first question the problem is not 'scope of allocated memory' but failure to pass value obtained from malloc back to main function. If function is declared like void fun(void*p) { p= malloc(1); } , you don't modify value of pointer where fun() is called. If you change in to
Expand|Select|Wrap|Line Numbers
  1. void fun(void**p)
  2. {*p = malloc(1);}
  3. main(){
  4. void *p;
  5. fun(&p);
  6. }
  7.  
it will work.
Jan 27 '09 #3
Banfa
9,065 Expert Mod 8TB
Except that for personal preference if nothing else is being returned I would return the pointer rather than pass a pointer to pointer

Expand|Select|Wrap|Line Numbers
  1. void *fun(void)
  2.  {
  3.     return malloc(1);
  4. }
  5.  
  6.  int main()
  7. {
  8.      void *p;
  9.      p = fun();
  10.  }
  11.  
Jan 27 '09 #4
Banfa
9,065 Expert Mod 8TB
ktwalker note that your examples 2 and 3 are not best practice. Any method that unnecessarily involves declaring global data is not best practice. Data declarations should have the scope limited to the minimum required to allow the program to operate.
Jan 27 '09 #5
donbock
2,426 Expert 2GB
Dynamic memory exists and is accessible from the time you malloc it until the moment you free it. It doesn't matter where you are in the function-call hierarchy.

However, you are more likely to get confused when you malloc memory in one function and free it in another -- you might forget to free it or you might inadvertently access it before it is malloc'ed or after it is freed.

It is good practice in a function that malloc's memory but doesn't free it, to loudly announce in the comments under that circumstances the function allocates memory and that it is the caller's responsibility to free the memory.

Likewise, it is good practice to announce loudly in the comments when a function destroys (frees) a block of memory that is passed in to it. The caller needs to be warned not to use that pointer again.
Jan 27 '09 #6
newb16, much thanks! Great tip! I confirmed this works for my example program.

Banfa, I'd like to return several arrays from the same function, thus why newb16's tip is so useful to me. And yes, I am quite aware globals are bad practice, but can be useful in some situations.

Donbock, thanks for the advice. Yes, from the example codes, it would appear that malloc'd memory inherits the "scope" of the pointer it gets attached to. I understand that it never gets freed itself until you free it.

Thanks everyone,
kris
Jan 27 '09 #7
donbock
2,426 Expert 2GB
@ktwalker
The scope of a pointer variable is controlled entirely by its declaration, not what it points at. For example, consider the following bug:
Expand|Select|Wrap|Line Numbers
  1.  ...
  2. int i;
  3. int *p;
  4. p = foobar(10);
  5. i = *p + 20;
  6. ...
  7. void foobar(int v) {
  8.    int a;
  9.    a = v;
  10.    return &a;
  11. }
Pointer variable 'p' is in-scope at line 5, but it points to deallocated memory. (What happens when you dereference 'p' is undefined.) Likewise, the scope of variable 'a' is not affected by the existence of a pointer that points to it.

It is similar for dynamic memory. The scope of allocated memory is from the instant malloc returns until the instant free is called. It doesn't matter if pointer variables point into the allocated memory or not.
Jan 27 '09 #8
From this back-n-forth and the examples, it is clear to me that one can use malloc to assign memory in any function anywhere to a globally declared pointer, and such memory will have an infinite scope and infinite duration until it is released with free. If the pointer is not global, it can then be in main(), and the address of that pointer can be passed as an argument into a function which assigns malloc'd memory to it (as newb16 explained). In this latter case, the duration of the allocated memory will also be infinite, but the scope will only be limited to within main().

Many thanks,
kris
Jan 27 '09 #9

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

Similar topics

5
by: August1 | last post by:
This is a short program that I have written from a text that demonstrates a class object variable created on the stack memory and another class object variable created on the heap memory. By way...
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...
10
by: s.subbarayan | last post by:
Dear all, I happen to come across this exciting inspiring article regarding memory leaks in this website: http://www.embedded.com/story/OEG20020222S0026 In this article the author mentions:...
13
by: hurry | last post by:
In order to avoid declaring static variables in a function I was asked to write a scratch memory. Reserve a block of memory outside the function and assigning pointers to the memory locations as...
6
by: pauldepstein | last post by:
Could anyone explain (by giving a URL possibly) how to solve problems of the form "How much memory does the following piece of code take?" For example, consider the declaration/definition ...
1
by: liuhaoran | last post by:
HI. i have a question about memory error. when i change double variable to float variable ,for example: int curGen = 0; double sum = 0; // m_iPopSize is int variable ,NewPop is a vector...
14
by: Michael Moreno | last post by:
Hello, Would you know what is best practice please between say: CODE 1: TimeSpan ts; for (i=0; i<1000; i++) {
7
by: Frank | last post by:
Hi, I have the following problem with dynamic memory: int main(){ for(){ int (**w)=new int *; for(m = 0; m < N1; m++) {
9
by: blangela | last post by:
Can somepoint me to a good discussion on the pros and cons of using #define versus a constant variable in your C+ application? Thanks, Bob
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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
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,...
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.