Search code examples
cmemorydynamic-memory-allocation

Will memory be allocated for a typedef structure pointer?


I have the following program, where i have a structure. I am going to assign some values to it and write it to a file. But the confusion here is, i have just declared a pointer to the structure and has not allocated memory. Then how does the variable assignment works? I am able to retrieve the values correctly from the file "/home/info"

#include <stdio.h>
#define FILEE "/home/info"

typedef struct my_info
{
   int i;
   int j;
   int k;
   int l;
}_my_info;

void main()
{
    _my_info *my_info;
    int fd;
    FILE *fp;
    my_info->i=100;
    my_info->j=300;
    my_info->k=200;
    my_info->l=400;
    fp = fopen(FILEE,"w");
    if (fp == NULL)
        printf("Error in opening file\n");
    fd=fwrite(my_info, sizeof(_my_info), 1, fp);
    if (fd<0)
        printf("Error while writing\n");
    fclose(fp);
}

Solution

  • When you declare my_info

    _my_info *my_info;
    

    it will have an undefined value. In your case, the value of my_info is within the range of valid memory addresses for RAM. So a write to it, and a read from it will take place.

    However, you don't know which other memory you are changing due to this. This may cause memory corruption, especially in larger programs.