简体   繁体   中英

Why are these integer values in my array changing?

I'm trying to read in data from a file and it seems to be read in correctly, however when I print the data 2 of the values change to 3. I'm very confused why this is happening. The file that is being read in looks like this:

John 7 0 1 3 2 0 1 1
Jack 3 4 4 1
Jane 5 3 2 3 0 4
Jenny 6 4 2 1 3 0 4
Jim 2 0 0
Joanna 4 1 2 4 2

The first number is just used to identify how many following numbers there are. For the first line, the first print statement reads it in as 0132011, but when the second print statement is executed it prints out 0132441. This also happens in the line with Jenny. It is read in as 421304, but printed out as 421300.

int* philRequests[numPhilosophers];
int numRequests[numPhilosophers];

    for(int i = 0; i < numPhilosophers; i++){
        fscanf(fp, "%s", buff);
        strcpy(names[i], buff);
        fscanf(fp, "%d", &numRequests[i]);
        philRequests[i] = (int *)malloc(numRequests[i] + 1);  //allocates memory by the number of requests each phil will make
        
        for(int x = 0; x < numRequests[i]; x++){
            fscanf(fp, "%d", &philRequests[i][x]);
            printf("\nAdding %d to %d %d", philRequests[i][x], i, x);
        }

    fgets(buff, 255, (FILE*)fp); //moves on to next line
    }

//displaying what was just read in
for(int i = 0; i < numPhilosophers; i++){
        for(int x = 0; x < numRequests[i]; x++){
            printf("\nReading %d from %d %d", philRequests[i][x], i , x);
        }
        printf("\n");
    }

Looks like an issue with overwriting memory because you aren't allocating enough space in your malloc call. Malloc allocates the specific number of Bytes you ask for. You ask for (numRequests[i]+i) Bytes. But you are actually looking for (numRequests[i]+i) pointers to int.

Try something like

philRequests[i] = malloc((numRequests[i] + 1)*sizeof(int*));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM