简体   繁体   中英

How do I define a struct and properly allocate memory for it in C?

I've recently started learning C and currently I'm working on a project which involves implementing a struct with two variables and I don't really know how to apparoach this.

The gist of it is I need to implement a struct which contains two variables, a pointer to an int array AND an int value which indicates the number of elements conatained within the array. The size of the array is declared upon the invocation of the constructor and is dependent on the input.

For the constructor I'm using a different function which recieves a string as input which is encoded into a decimal code. Also this function recieves another input which is a pointer to an int array (the pointer defined in the struct) and the problem is I'm using the malloc() function to allocate memory for it but I dont really understand how and when to use the free() function properly.

So, the questions are:

  1. When am I supposed to free the allocated memory? (assuming I need this struct for later use throughout the program's running time)
  2. What are the best ways to avoid memory leaks? What should you look out for?

It's unclear whether you're expected to manage the memory of the array inside, but this is functionally the setup you need for allocating the containing structure.

#include <malloc.h>
#include <stdio.h>

struct my_struct {
   size_t num_entries;
   int *array;
};

int main() {
    struct my_struct *storage = malloc(sizeof(struct my_struct));
    storage->num_entries = 4;

    storage->array = malloc(sizeof(int) * storage->num_entries);
    storage->array[0] = 1;
    storage->array[3] = 2;

    printf("allocated %ld entries\n", storage->num_entries);
    printf("entry #4 (index=3): %d\n", storage->array[3]);

    free(storage->array); /* MUST be first! */
    free(storage);
    storage = 0; /* safety to ensure you can't read the freed memory later */
}

if you're responsible for freeing the internal storage array, then you must free it first before freeing the containing memory.

The biggest key to memory management: only one part of the code at any time "owns" the memory in the pointer and is responsible for freeing it or passing it to something else that will.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM