Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1097359
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T00:25:16+00:00 2026-05-17T00:25:16+00:00

I just finished working out a memory allocation problem with the current program I’m

  • 0

I just finished working out a memory allocation problem with the current program I’m writing, but I am not happy with what I had to do to fix it.

In my program, I was building up an array of structs, reallocating space for the array every time I wanted to add a struct to it. Here is a generic version of my struct and the function that would add a struct to the array:

typedef struct Example {
    const char* name;
    int (*func)(int, int);
    int bool_switch;
}

int add_struct_to_array( Example **example_array, int *ex_array_size, int name, int (*func)(int, int), int bool_switch)
{
    // first, make a new struct
    Example *new_example = (Example *) calloc( 1, sizeof( Example ) );
    if( new_example != NULL ) {
        new_example->name = name;
        new_example->func = func;
        new_example->bool_switch = bool_switch;
        ( *ex_array_size )++;
    } else {
        printf( "Errror allocating %s\n", name );
        exit( -1 );
    }

    // now, realloc the array of structs and add the new member to it
    Example **temp_example_array = ( Example** )realloc( example_array, ( *ex_array_size ) * sizeof( Example* ) );
    if( temp_example_array != NULL ) {
        example_array = temp_example_array;
        example_array[ ( *ex_array_size ) - 1 ] = new_example;
    } else {
        printf( "Reallocation failed\n" )
        exit( -1 );
    }
    return 0;
}

And here is where I would call the functions (notice how I’m initially allocating the array of structs, cuz that’s where the problem was)

#include "example_struct.h"

int main( int argc, char **argv )
{
    int ex_array_size = 0;
    Example **example_array = ( Example** )calloc( 0, sizeof( Example* ) );

    add_struct_to_array( example_array, &ex_array_size, "name", &function, 1 );
    ...
    ...
    add_struct_to_array( example_array, &ex_array_size, "other_name", &other_func, 0 );

    /* Do stuff here */

    example_array_free( example_array );

    return 0;
}

In my ignorance, I apparently thought that allocating the array with size 0 would be ok, since it was initially empty, and I could add structs to it after that. Obviously, this did not work, I would get runtime errors about error for object 0x100100080: pointer being reallocated was not allocated. The example_array was at address 0x100100080 and the first struct I would allocate for would be at address 0x100100090, and after a few reallocations the example_array would run out of room.

So, finally, to my question. I solved this problem by allocating more space for my example_array than I would need, but that seems very inelegant. Is there a better way to do this?

**EDIT**

Ok, so from the looks of most of the responses, I shouldn’t be using pointers to pointers. So, I am trying it a slightly different way, mixing pmg and crypto‘s responses. Here is my code now:

/* example_struct.h */
int add_struct_to_array( Example *example_array, int *ex_array_size, int name, int (*func)(int, int), int bool_switch)
{
    Example temp_example_array = realloc( example_array, ( ( *ex_array_size ) + 1 ) * sizeof( Example ) );

    if( temp_example_array != NULL ) {
        example_array = temp_example_array;
        Example new_example;
        new_example.name = name;
        new_example.func = func;
        new_example.bool_switch = bool_switch;
        example_array[ ( *ex_array_size ) ] = new_example;
        ++( *ex_array_size );
    } else {
        fprintf( stderr, "Error reallocating for %s", name );
        exit( -1 );
    }
    return 0;
}



/* main.c */
...
...
#include "example_struct.h"
int main( int argc, char **argv )
{
    int ex_array_size = 0;
    Example *example_array = NULL;

    add_struct_to_array( example_array, &ex_array_size, "name", &func, 1 );
    add_struct_to_array( ... );
    ...
    add_struct_to_array( example_array, &ex_array_size, "other name", &other_func, 0 );

    example_free( example_array );
}

Everything compiles and realloc‘s alright, but I have trouble accessing the structs within the array.

/* main.c */
...
...
#include "example_struct.h"
int main( int argc, char **argv )
{
    int ex_array_size = 0;
    Example *example_array = NULL;

    add_struct_to_array( example_array, &ex_array_size, "name", &func, 1 );
    add_struct_to_array( ... );
    ...
    add_struct_to_array( example_array, &ex_array_size, "other name", &other_func, 0 );


    printf( "%s\n", example_array[0].name ) /* Segfault */


    example_free( example_array );
}

Thanks again for all your help.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T00:25:17+00:00Added an answer on May 17, 2026 at 12:25 am

    Here’s a minimum working version (with C++ keywords for lots of identifiers — I kinda apologize, but it looked fun when I started and I couldn’t stop or go back midway through) which also runs on ideone ( http://ideone.com/iMByR )

    #include <stdio.h>
    #include <stdlib.h>
    
    struct protected {
      int this;
      int (*catch)(int, int);
      int friend;
    };
    
    int catch(int mutable, int virtual) {
      return mutable + virtual;
    }
    
    struct protected *add_one(struct protected **private,
                              int *explicit, int using,
                              int (*catch)(int, int), int friend) {
      struct protected *new;
    
      new = realloc(*private, (*explicit + 1) * sizeof *new);
      if (new) {
        *private = new;
        (*private)[*explicit].this = using;
        (*private)[*explicit].catch = catch;
        (*private)[*explicit].friend = friend;
        (*explicit)++;
      }
      return new;
    }
    
    /* create an array of structs using dynamic memory */
    /* keep adding elements to it, and growing it as needed */
    int main(void) {
      int using;
      /* explicit contains the number of elements in the try array */
      int explicit = 0;
      struct protected *try = NULL;
    
      /* create and grow */
      for (using = 0; using < 7; using++) {
        if (add_one(&try, &explicit, using + 1, catch, 0) == NULL) {
          fprintf(stderr, "failure at loop %d\n", using);
          exit(EXIT_FAILURE);
        }
      }
    
      /* verify */
      for (using = 0; using < explicit; using++) {
        printf("%d: %d\n", using, try[using].this);
      }
    
      free(try);
      return 0;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I just finished a homework problem for Computer Science 1 (yes, it's homework, but
I've just finished working for a client which has burnt millions on a project
So I just finished working the project at http://msdn.microsoft.com/en-us/data/gg685489 . I am trying to
Just finished up my first mvc4 app. Everything is working great until I deploy
I just recently finished Michael Feathers' book Working Effectively with Legacy Code . It
I just finished this script it works well, but I am struggling to pass
I'm working with .Net using VB and have just finished a website project and
Working on a project, nearly finished and just tidying up the HTML and I
So I'm a fairly decent javascript programmer and I've just recently finished working on
I have finished the majority of my application that I am working on, but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.