2

Hey I'm not sure why when I pass a Struct array to a function; When I try to access it's members it prints random number. Below the statement "printf("%d\n", netTopo[0].nodes[1]);" works correct but I'm in the function and try print the same data, it prints a bunch of random number? Not sure what I'm doing wrong.

int main(int argc, char *argv[]) {

if (argc != 3){
        printf("Incorrect command line arguments. Required 2 files.\n");
        exit(-1);
    }

    FILE *netFile, *schFile; // put into a loop
    netFile = fopen(argv[1], "r");
    schFile = fopen(argv[2], "r");

    int *sched = getSchedFile(schFile);

    struct nodeInfo *netTopo = getTopology(netFile);
    printf("%d\n", netTopo[0].nodes[1]);

    int nodeSocks[nodeCount];
    for (int i=0; i<nodeCount; i++){
        nodeSocks[i]=getSocketNo();
    }

    get_elapsed_time(); // start clock

    for (int i=0; i<nodeCount; i++){
        if (fork()==0){
            nodeExecution(i, nodeSocks, netTopo, sched);
            exit(0);
        }
    }
}

void nodeExecution(int id, int nodes[], struct nodeInfo *netTopo, int *schd){
    printf("%d\n", netTopo[0].nodes[1]);
......
2
  • can you post the complete code ? Commented Oct 12, 2013 at 7:12
  • 0) for (int i=0; i<nodeCount; i++){ if (fork()==0){ what is nodecount? 1) netTopo[id].nodes = malloc(totLinks * sizeof(int)+1); 2) for(int i=1; i<=totLinks; i++) { Commented Oct 12, 2013 at 7:44

1 Answer 1

2

so you return a pointer to local var on stack from getTopology()? that's the bug.

netTopo is on stack and when you return from getTopology() there are other function calls which would reuse the memory region where netTopo is stored. That memory is modified and you get different output when calling nodeExecution()

ADD: to fix this you may allocate memory in getTopology():

struct nodeInfo* getTopology(FILE *file){
    int id, digit=0, totLinks=0;
    fscanf(file, "%d", &nodeCount);
    struct nodeInfo * netTopo = malloc(sizeof(struct nodeInfo)*nodeCount);

  ....
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that.. So to fix it maybe pass a pointer of a struct to the function instead?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.