tables initiated with pointers issues !

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Wilson014
    New Member
    • Apr 2014
    • 5

    tables initiated with pointers issues !

    Hi all,

    I have a serious trouble to which I found no explanation, if someone can help me this would save me really:
    In my code I have lots of structures. I try to make tables of structures and then get access to elements of the structures to use them all along my code: here is an example to clarify things
    Code:
    typedef struct {
    
    Fabric **closfabric;
    
    }Network;
    Net is part of another structure called Switch and Fabric itself is a composed structure.
    I have done the following
    Code:
    aSwitch->net.closfabric = (Fabric **)malloc(3* sizeof(Fabric *));
    
    aSwitch->net.closfabric[0] = (Fabric *)malloc(m * sizeof(Fabric ));
    aSwitch->net.closfabric[1] = (Fabric *)malloc(k * sizeof(Fabric ));
    aSwitch->net.closfabric[2] = (Fabric *)malloc(m * sizeof(Fabric ));
    The compilation returns a segmentation fault because aSwitch->net.closfabr ic is NULL (0) .

    surprisingly, in other codes the same analogy of using tables made of double pointers works perfectly with no problems and I have no problem of core dumped and NULL pointers.

    I am lost and I cannot understand why am I getting this problem. It is the case whenever I try to use large dimension tables (tab *** struct for example)

    Regards,

    Monson
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    Is it possible that you are running out of memory, causing malloc to return NULL?

    In any case, your code should deal with that possibility - every call to malloc should be followed by a snippet that tests for failure-to-allocate and deals with the situation appropriately.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      This compiles:
      Code:
      Network net;
      	Network* aSwitch = &net;
      	int m = 3;
      	int k = 3;
      	aSwitch->closfabric = (Fabric **)malloc(3 * sizeof(Fabric *));
      
      	aSwitch->closfabric[0] = (Fabric *)malloc(m * sizeof(Fabric));
      	aSwitch->closfabric[1] = (Fabric *)malloc(k * sizeof(Fabric));
      	aSwitch->closfabric[2] = (Fabric *)malloc(m * sizeof(Fabric));
      but I may not clearly understand what net is.

      Also, you have to be certain aSwitch is not NULL.

      Comment

      Working...