Thread: Dynamic allocation inside function

  1. #1
    Caution: Wet Floor
    Join Date
    May 2006
    Posts
    55

    Dynamic allocation inside function

    File allocate.c:

    Code:
    void f(double **X, int *A, size_t sz) {
    
        /* ... */
    
    X = malloc (sz * sizeof(double *));
    
    for (i=0;i<sz;i++) {*X=malloc (A[i]*sizeof (double)); *X++;}
    
    }
    
    int main () {
    
          double **Y = 0;
          double A[5]={1, 2, 3, 4, 5};
          size_t sz = 5;
    
           f(Y);
    
    }
    % ./allocate
    Segmentation fault

    Does f() actually allocate space for Y? I'd like to do it inside of a function, if possible. Any suggestions?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    That code doesn't compile. You have an f with three arguments, and you call it with one. With a pointer, you can change the value of that object type in a function, and have it retain the change outside of a given function. So if you want a pointer to a pointer to have its value changed through a function, you need a pointer to a pointer to a pointer to a type.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    Yep! f() allocates space for X; but there are quite a few things wrong with this code snippet.
    Function f() takes 3 parameters, yet you are calling it with a single argument inside of main().
    Though X and *X point to blocks of storage but *X++ does not and the cause of your segfault.

  4. #4
    Caution: Wet Floor
    Join Date
    May 2006
    Posts
    55
    Thanks. Yeah, I meant
    Code:
    f(Y, A, sz);
    Can you actually allocate space for Y through the call to f(), though? Y is initialized in main() but no space is allocated before f() is called. Does the call actually allocate the space for Y?

  5. #5
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    As long as f() returns X, which then is made available to Y in main().

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 04-11-2009, 09:44 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Change this program so it uses function??
    By stormfront in forum C Programming
    Replies: 8
    Last Post: 11-01-2005, 08:55 AM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM