Search code examples
carraysstringstructure

segmentation fault memory dumped


I have following code. I got a error that 'segmentation fault memory dumped' when I write an array 'ADDRESS.Person' to any value. any one please help me to solve a problem.

#include <stdio.h>

typedef struct
{
    char Person[15];
} stName;

typedef struct
{
    stName      Name;
} stSociety;

stSociety* SOCIETY;

#define ADDRESS    SOCIETY->Name


int main()
{

    int i;

    for (i=0; i<32; i++)
    {
        ADDRESS.Person[i] = 0;
    }

    printf("ADDRESS.Person=%s\n", ADDRESS.Person);

    printf("Finished");
    return 0;
}

Solution

  • You have just declared the structs , you need to create them as well and hence,SOCIETY is pointing to nothing.Also you are iterating through 32 values whereas there are only 15 in the char array.I have modifed the code ,hopefully you will get an idea here

    #include <stdio.h>
    
    typedef struct
    {
        char Person[15];
    } stName;
    
    typedef struct
    {
        stName      Name;
    } stSociety;
    
    #define ADDRESS    SOCIETY->Name
    
    
    int main()
    {
    
    stSociety* SOCIETY,sample;
    SOCIETY = &sample;
    
    
        int i;
    
        for (i=0; i<15; i++)
        {
           ADDRESS.Person[i] = '0';
    
        }
    
        printf("ADDRESS.Person=%s\n", ADDRESS.Person);
    
        printf("Finished");
        return 0;
    }