This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

An error in allocation

We have an issue with this code


struct foo {
 int NumberOfPointers;

 char *Pointers[1];
} xx;

// Allocate A Block Of Pool With Room For 100 Pointers

myHunkyStuff = malloc( sizeof(long) + 100 * sizeof (char *) );

Can anyone explain?

The H Matherson Crew

Parents
  • Apart for an obvious error/typo in the code, the task itself is straightforward:

    
    struct foo {
     int NumberOfPointers;
    
     char *Pointers[1];
    } xx;
    
    // Allocate A Block Of Pool With Room For 100 Pointers
    
    myHunkyStuff = malloc( sizeof(xx) + (100-1)*sizeof (char *) );
    
    

    You want the size of the overall structure (along with any padding that might be present between NumOfPointers and Pointers) plus an array of the 'extra to the one already in' the structure.

Reply
  • Apart for an obvious error/typo in the code, the task itself is straightforward:

    
    struct foo {
     int NumberOfPointers;
    
     char *Pointers[1];
    } xx;
    
    // Allocate A Block Of Pool With Room For 100 Pointers
    
    myHunkyStuff = malloc( sizeof(xx) + (100-1)*sizeof (char *) );
    
    

    You want the size of the overall structure (along with any padding that might be present between NumOfPointers and Pointers) plus an array of the 'extra to the one already in' the structure.

Children
No data