memory versus variable scope

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ktwalker
    New Member
    • Jan 2009
    • 4

    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
  • ktwalker
    New Member
    • Jan 2009
    • 4

    #2
    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

    Comment

    • newb16
      Contributor
      • Jul 2008
      • 687

      #3
      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
      Code:
      void fun(void**p)
      {*p = malloc(1);}
      main(){
      void *p;
      fun(&p);
      }
      it will work.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Except that for personal preference if nothing else is being returned I would return the pointer rather than pass a pointer to pointer

        Code:
        void *fun(void)
         {
            return malloc(1);
        }
        
         int main()
        {
             void *p;
             p = fun();
         }

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          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.

          Comment

          • donbock
            Recognized Expert Top Contributor
            • Mar 2008
            • 2427

            #6
            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.

            Comment

            • ktwalker
              New Member
              • Jan 2009
              • 4

              #7
              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

              Comment

              • donbock
                Recognized Expert Top Contributor
                • Mar 2008
                • 2427

                #8
                Originally posted by ktwalker
                ... 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.
                The scope of a pointer variable is controlled entirely by its declaration, not what it points at. For example, consider the following bug:
                Code:
                 ...
                int i;
                int *p;
                p = foobar(10);
                i = *p + 20;
                ...
                void foobar(int v) {
                   int a;
                   a = v;
                   return &a;
                }
                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.

                Comment

                • ktwalker
                  New Member
                  • Jan 2009
                  • 4

                  #9
                  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

                  Comment

                  Working...