Passing struct to functions

2019-07-16 01:25发布

问题:

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]);
......

回答1:

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);

  ....