Search code examples
cmemory-managementmallocstructurefree

How do I create a dynamic memory allocation using malloc for structures in C?


I want to allocate memory for "title" dynamically as I don't know how long the titles will be. I have the following code:

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

struct film {
    char title[500];
    int year;
    int duration;
    int earnings;
};

void main() {
    int n;
    scanf("%d", &n);
    int array[n], i = 0;
    struct film user[n];

    while (i < n) {
        scanf("%s", &user[i].title);
        scanf("%d", &user[i].year);
        scanf("%d", &user[i].duration);
        scanf("%d", &user[i].earnings);
        i += 1;
    }
}

I tried replacing:

char title[500];

with:

char *title = (char*)malloc(sizeof(char));

However, it didn't work. It says that it expects something else before "=". Also, how do I scanf the input from the user for title if it is dynamically allocated?

How do I free the memory later? I assume it's as below:

void freememory(struct film target,  n) { //n is size of structure
    int i = 0;
    while (i < n) {
        free(target[i].title);
        i += 1;
    }

Correct?


Solution

  • The struct part is just a declaration, you can't execute any code there. malloc can only be executed at run-time. Meaning your struct should be

    typedef struct {
        char* title;
        int year;
        int duration;
        int earnings;
    } film;
    

    Then later

    film user[n];
    
    for(int i=0; i<n; i++)
    {
      char title [200];
      scanf("%s", title);  // scan to temporary buffer since we don't know length
      ...
    
      user[i]->title = malloc(strlen(title) + 1); // alloc just as much as is needed
    }
    

    Your free() code works.

    Please note that this code is fairly naive; micro-managing memory like this might not be the best idea in real applications. Picking a fixed max string length instead and then making sure that the input doesn't exceed it might be a better plan, by using fgets instead of scanf.