简体   繁体   中英

What is the difference between using malloc to allocate memory to a struct pointer and pointing a struct pointer to a struct's memory address?

What is the difference between these two snippets of code?

// Structure
struct file {
    int fileSize;
};

int main(void) {
    // Variables
    struct file *pFile = (struct file*) malloc(sizeof(struct file)); // Declare pointer of type struct file and allocate enough room

    pFile->fileSize = 5;

    free(pFile);

    return 0;
}

and

// Structure
struct file {
    int fileSize;
} file1;

int main(void) {
    // Variables
    struct file *pFile = &file1; // Declare pointer of type struct file and point to file1 struct

    pFile->fileSize = 5;

    return 0;
}

Is there something big I'm missing here? I'm thinking maybe face value wise these are the same but the underlying memory allocation is different? I just can't grasp it.

There are several differences here:

  • With malloc you can repeat the call multiple times, and get new valid memory area for your struct; there is only one statically allocated struct
  • Memory obtained through malloc needs to be freed at the end; statically allocated memory does not need freeing
  • Statically allocated struct is visible from multiple functions inside the translation unit; memory from malloc is not shared with other functions unless you pass a pointer to them explicitly.

In your first snippet pFile points to dynamically-allocated memory.

In your second snippet, pFile points to a global variable.

Other than the fact that you need to free the dynamic one yourself (which you haven't by the way), the way you interact with the struct is exactly the same in either case.

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