'How to fix and understand this Segmentation Fault (core dump) error? I cannot comprehend it whatsoever
I am tasked with creating a C code that does what page-replacement algorithms do. The code is barely 200 lines, so I will try to send some portions and hopefully, you can still be able to help me without the whole code. I create a global int array and I modify it inside the if statement in main. I have tried everything to debug this, and I still cannot comprehend why it runs perfectly with the unmodified array, but it Core Dumps when it is modified. It burdens me because the whole array is actually changed, but it gives a segmentation fault. If the code actually is writing to that memory, why does it still give a Segmentation Fault?
Here is a good portion of the whole code:
#include <stdio.h>
#include <stdlib.h>
// GLOBAL VARIABLES
int stringNum = 100;
int pageReferences[100] = {2, 8, 7, 2, 0, 3, 1, 7, 3, 1, 9, 3, 6, 1, 8, 4, 5, 1, 8, 8, 3, 4, 4, 3, 4, 2, 0, 6, 6, 7, 0, 1, 0, 9, 3, 6, 4, 6, 8, 0, 4, 6, 2, 3, 5, 7, 8, 0, 3, 2, 0, 0, 0, 4, 6, 9, 1, 4, 3, 8, 8, 0, 0, 9, 7, 0, 7, 0, 9, 7, 7, 3, 8, 8, 9, 2, 7, 2, 1, 2, 0, 9, 1, 1, 1, 5, 0, 7, 1, 4, 9, 1, 9, 5, 8, 4, 4, 7, 9, 6};
int frame[15];
// PROTOTYPES
void fifo(int frameSize);
void lru(int frameSize);
void opt(int frameSize);
// MY MAIN
void main(int argc, char*argv[]) {
int frameSize;
if (argc == 2) {
frameSize = atoi(argv[1]);
}
else if (argc == 3) {
frameSize = atoi(argv[1]);
unsigned int seed = atoi(argv[2]);
srand(seed);
for (int i = 0; i < 100; i++){
pageReferences[i] = (rand() % 10);
}
}
else
printf("Usability: Input 1 or 2 numbers. First number is Frame size and Second number is the Seed for random.\n");
fifo(frameSize);
lru(frameSize);
opt(frameSize);
}
I have had help from other people and none can identify why it acts the way it does. The issue seems to be the MODIFICATION of the array, but I have not yet found a way to fix it, even if I declare it inside the if statements as local variables and give the array as parameters to the functions. I wish to have a default array and change its contents if necessary.
How can I fix this? Does using malloc or making it a pointer help with anything?
Solution 1:[1]
I doubt that the writing to the array causes your issue. The global array has places for 100 ints and thats exactly the amount of ints your loop writes into. So you don't seem to go out of bounds on that.
Are you sure that the loop doesn't just finish and you get the coredump because the functions you call afterwards point to invalid addresses because they were not defined yet? I mean in that case your compiler should already complain before you try to run this, but it's the only thing missing here at first glance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arwez |
