/*
 * main.c
 */

#include <stddef.h>

// A complex linked-list set of data reduced to the bare elements to generate
// A segment fault. Two structures: Structure A can point to B, and B to A.
// In this example, A1 points to B1 which points to A2 which points to B2
// which points back to A1. So starting at any of these structures, one can
// walk the chain all the way around the ring and up at the beginning.
//
// The actual data structures I've used in many projects since 2004 are much
// more complicated, but this example provides the essence that generates a
// segmentation fault when I try to compile it. I've used the same structures
// with several different compilers and processor families, including
// Code Composer Studio 3.3 targeting a TI SM320F2812, as well as various
// 8 and 16 bit processors, as well as Windows apps. This is the first time
// these structures have given me problems.

// To generate the issue, I created a new CCS v5.1 empty project for an
// MSP430F2254, used all default project settings, and inserted this code.

// Forward declarations so each structure can reference the other.
struct A_Struct;
struct B_Struct;


// Structure A - only the minimum required to reference B, no useful data.
struct A_Struct
{
   const struct B_Struct*  B;
};


// Structure B - only the minimum required to reference A, no useful data.
struct B_Struct
{
   const struct A_Struct*  A;
};


// Forward declarations of B_Struct instances so circular links can be made.
static const struct B_Struct B1;
static const struct B_Struct B2;

// Define two A structs that point to corresponding B structs.
static const struct A_Struct A1 = {&B1};
static const struct A_Struct A2 = {&B2};

// Define two B structs that point to opposite A structs.
static const struct B_Struct B1 = {&A2};
static const struct B_Struct B2 = {&A1};


void main(void) {

   struct B_Struct x;      // Declare a instance of one of the structs

   x.A = &A1;              // Point the struct to the circular link.
                           // This generates a reference to the ring that
                           // results in a segmentation fault. Don't reference
                           // the ring, or don't include circular references
                           // and it compiles properly.

}
