2

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?

Cloud
  • 18,753
  • 15
  • 79
  • 153
user2861799
  • 115
  • 1
  • 2
  • 7
  • 1
    It's not clear what you're asking. Are you talking about using `malloc` to allocate space for a single struct object? Does `struct foo *ptr = malloc(sizeof *ptr);` address what you're trying to do? – Keith Thompson Mar 26 '14 at 01:24
  • malloc(sizeof(struct T)) always allocates exactly enough space for the data in one struct T. Not more, but also not less. No need to check. If the "system memory", i.e. the heap is insufficient to allow reserving that much memory malloc will return NULL which _should_ be checked. – Peter - Reinstate Monica Mar 26 '14 at 01:25
  • yes malloc and @PeterSchneider my code just started getting slower and slower so i was wondering is it because i have the struct too long on the heap ? – user2861799 Mar 26 '14 at 01:26
  • Sure, if you allocate GBytes of data you may see your machine start swapping unused memory to disk in order to free RAM for the allocations. But that would have to be lots of allocations. It's good practice to free() the memory when not needed any longer. – Peter - Reinstate Monica Mar 26 '14 at 01:29

1 Answers1

7

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>
Community
  • 1
  • 1
Cloud
  • 18,753
  • 15
  • 79
  • 153
  • Strictly spoken, your line marked `// Static allocation, no cleanup required` is a bit misleading because static has these special meanings in C, none of which applies here. staticStruct is not static but _automatic_. – Peter - Reinstate Monica Mar 26 '14 at 01:31
  • @Dogbert Suppose you need to pass that allocated struct around you program for at least 5 functions to use – user2861799 Mar 26 '14 at 01:32
  • @user2861799 It doesn't matter how many functions need to use it. When you pass either the struct itself or a pointer to the struct, the latter method being preferred, you're given a copy of the argument anyways (ie: passing by value as opposed to passing by reference). If you have some example code you'd care to pass along, I could comment further. – Cloud Mar 26 '14 at 01:35
  • @Dogbert Just to clarify: When you pass a pointer, you _do_ pass a copy of the argument, which is the _pointer._ You _do not_ pass a copy of the struct. – Peter - Reinstate Monica Mar 26 '14 at 01:37
  • @PeterSchneider By "static" I'm referring to the variable is stored in the code segment on the stack rather than on the heap. Not quite 100% accurate, but sufficient for the question at hand. I included an additional reference to a separate post of mine that explains this quite thoroughly. – Cloud Mar 26 '14 at 01:37
  • @Dogbert your reference is specific to more than one struct correct? but the one i used is a struct called acc which had the info for the acc , so i passed it around in all functions that needed direct contact with it , such as deposit withdraw, check. – user2861799 Mar 26 '14 at 01:38
  • @PeterSchneider I disagree on that. In ANSI C, you do indeed pass a copy of the whole struct, which is stored on the stack. If you have an absurdly large struct and you are returning it from a function or accepting it as a formal function parameter, you can indeed run out of stack space. http://stackoverflow.com/questions/161788/are-there-any-downsides-to-passing-structs-by-value-in-c-rather-than-passing-a – Cloud Mar 26 '14 at 01:39
  • @user2861799 Correct. My example and discussion above is generic. If you just need a single instance of a struct to be passed to multiple functions, you're fine. If you need multiple instances of a single type of struct (ie: multiple accounts, one for Bob, one for Charlie, etc) then you would either create an array-of-structs, or a linked list of structs, etc. – Cloud Mar 26 '14 at 01:40
  • @Dogbert:Why don't you stick with precise words for things. A local variable certainly is not stored in the code segment which most people use to name the place where the executable machine code of a program resides. – Peter - Reinstate Monica Mar 26 '14 at 01:42
  • Thanks they didnt teach us linked list seems complicated though – user2861799 Mar 26 '14 at 01:43
  • @PeterSchneider That was a typo which is too late to correct (I meant "data" segment). – Cloud Mar 26 '14 at 01:44
  • @user2861799 They're not as complicated as they might seem. If you want to increase the number of structs in an array, your only choice is to create a new, bigger array, and copy the old data into the new one, and clean up the old smaller array. – Cloud Mar 26 '14 at 01:44
  • @PeterSchneider "static" allocation is effectively synonymous with "automatic" allocation for all intents and purposes in my industry. http://stackoverflow.com/questions/8385322/difference-between-static-memory-allocation-and-dynamic-memory-allocation Additionally, it is technically possible to store variables in the code segment, but if you try to write to them, you get a seg fault. – Cloud Mar 26 '14 at 01:45
  • @Dogbert But it is not in the data segment either, cf e.g. http://www.hep.wisc.edu/~pinghc/Process_Memory.htm, http://www.cs.uwm.edu/classes/cs315/Bacon/Lecture/HTML/ch10s04.html or even http://en.wikipedia.org/wiki/Data_segment (although I could just have written that myself). Local variables (and staticStruct is local, even if it is local to main) reside on the _stack_ which is a distinct memory area. – Peter - Reinstate Monica Mar 26 '14 at 01:51
  • @PeterSchneider In this example, yes, they will reside on the stack, but if they were defined outside of `main()`, they could potentially be stored in the RO and R/W sections of the data segment. – Cloud Mar 26 '14 at 02:16