user2861799
user2861799

Reputation: 225

C struct and memory allocation

When you allocate space for memory how do you tell if you need to allocate more space for it? Is there a check or so you can do on your new memory to make sure it is doing OK? ( allocated memory for a struct).

Because what i am thinking is that a struct is a set amount of data and even though I pass it around a lot it should never need more than the size of the struct correct?

Upvotes: 3

Views: 25761

Answers (1)

Cloud
Cloud

Reputation: 19331

If you're just using a simple struct, you don't need more memory allocated for it as time goes on. You just create the struct, use it, and clean it up if required. If you are dynamically allocating your struct (ie: with malloc), then you test the value of the pointer-to-struct you create and see if it is NULL. If it is NULL, then the memory allocation failed, and you can either retry, or abandon further operations (ie: exit on error condition).

#include <stdio.h>

typedef struct myStruct {
  int i;
  char c;
} myStruct;

int main(void) {
  // Static allocation, no cleanup required
  myStruct staticStruct;
  staticStruct.i = 0;
  staticStruct.c = 'c';

  // Dynamic allocation, requires cleanup
  myStruct* dynamicStruct;
  dynamicStruct = malloc(sizeof(myStruct));
  if (dynamicStruct == NULL) {
    printf("Memory allocation error!\n");
    return (-1);
  } else {
    printf("Successfully allocated memory!\n");
  }

  dynamicStruct->i = 1;
  dynamicStruct->c = 'd';
  free(dynamicStruct);  // Release allocated memory
  dynamicStruct = NULL; // Somewhat common practise, though not 100% necessary
  return 0;
}

Now, if you need to create an array of dynamically allocated structs, and you've used them all up, and need more, you'd likely be best off with a slightly more complicated approach, like a dynamically allocated linked list of structs. A good example can be found in the "References" section below. Also, I've included a link to a somewhat related question I answered on memory allocation in C. It has some good examples that might also help clear up this topic for you.

References


  1. C Linked List Data Structure Explained with an Example C Program, Accessed 2014-03-25, <http://www.thegeekstuff.com/2012/08/c-linked-list-example/>
  2. Difference between declared string and allocated string, Accessed 2014-03-25, <https://stackoverflow.com/questions/16021454/difference-between-declared-string-and-allocated-string>

Upvotes: 8

Related Questions