Segmentation Fault in unexpected location when I add a for loop to main
I wrote the code below, in a C file called Practice_3.c to practice my C which I am quite rusty at. There are standard inputs at the top, a few function declarations/definitions and a few structs. Now, if you notice the very bottom of the code, I have a for loop that basically does nothing relevant (or at least I thought so). However, with this for-loop here this is my output.
type herHello, World
b is now: 5
The 0th element of the array is: 0.
The 1th element of the array is: 1.
The 2th element of the array is: 2.
The 3th element of the array is: 3.
The 4th element of the array is: 4.
The 5th element of the array is: 5.
The 6th element of the array is: 6.
The 7th element of the array is: 7.
The 8th element of the array is: 8.
The 9th element of the array is: 9.
3
Value is: 13
Value is: 100
zsh: segmentation fault ./Practice_3e
Now, if I remove the for-loop and just leave the print statement, the program runs normally But with this for-loop at the bottom (and I have even tried commenting out the print statement inside) I get this segmentation fault. What further confuses me, is if you look to see where the segmentation fault is, it occurs after the print statements "Value is:..." Now, when I remove the for-loop at the bottom, the output becomes the following:
tHello, World
b is now: 5
The 0th element of the array is: 0.
The 1th element of the array is: 1.
The 2th element of the array is: 2.
The 3th element of the array is: 3.
The 4th element of the array is: 4.
The 5th element of the array is: 5.
The 6th element of the array is: 6.
The 7th element of the array is: 7.
The 8th element of the array is: 8.
The 9th element of the array is: 9.
3
Value is: 13
d
0
The y coordinate of point1 is: -1
The coordinates for point4 are 7 and 12
For this one our coordinates are 10
The bottom left of our rectangle is 38
Arr of 0 is: -4.
The 0th element of arrAgain is: -8
The 1th element of arrAgain is: -3
The 2th element of arrAgain is: 0
The 3th element of arrAgain is: 4
The 4th element of arrAgain is: 7
The 5th element of arrAgain is: 11
The 6th element of arrAgain is: 12
The 7th element of ype here
Note that 1) given my code below in the part where I print the "value is:..." the correct working of the code only prints "Value is: 13" and does not print "Value is: 100" afterwards as the conditions to continue within that loop are not met. 2) This region of code is NOT close to the lines of code which cause this issue which are THE FOR LOOP AT THE BOTTOM. It isn't one of the other for loops causing this, it is just that for loop. That said, if I copy/paste that loop somewhere else within main the error persists, but if I remove the loop and put in a different statement (say a print statement) there is no segmentation fault.
I cannot figure out why an isolated for-loop in main has the effect of causing a seg-fault and causing the set-fault in an earlier and unrelated section of main. Why does adding a loop with "junk" / "hello world" type content cause the "Value is:..." / node struct to give me a seg fault.
This is so strange. I have restarted VS-Code, I have checked my compiler (gcc) but as long as there is a for-loop in main this issue arises. My irrational mind is almost wondering if I reached the upper-bound for the number of for-loops allowed in main which is then causing this error. I am beyond confused why this would be the case, the interactions between these areas of code and...well, everything about this.
Here is the code. It is only this file, there are no linked files or header files or anything. If anyone has any idea please let me know.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct node {
int val;
struct node* left;
struct node* right;
};
void swap(int* x, int* y){
int temp = *y;
*y = *x;
*x = temp;
}
int modular(int base, int val){
if(val < 0){
return modular(base, -val);
}
else if(val < base){
return val;
}
else {
return modular(base, val-base);
}
}
struct point {
int x;
int y;
} point1, point2;
struct point makePoint(int x, int y){
struct point temp;
temp.x = x;
temp.y=y;
return temp;
}
struct rect {
struct point pt1;
struct point pt2;
} myRect;
void insertionSort(int* head, int arrLength){
for(int i = 0; i < arrLength; i++){
for(int j = i+1; j < arrLength; j++){
//printf("Here we have %d\n", *(head+j));
if(*(head + j) < *(head + i)){
int temp = *(head + j);
*(head + j) = *(head + i);
*(head + i) = temp;
}
}
//printf("We've reached here...");
}
return;
}
int main(){
printf("Hello, World");
int a = 5;
int b = 3;
swap(&a, &b);
printf("\n b is now: %d\n", b);
int arr[10];
int l = sizeof(arr)/sizeof(arr[0]);
for(int i = 0; i < l; i++) {
arr[i] = i;
}
for(int i = 0; i < l; i++){
printf("\nThe %dth element of the array is: %d.", i, *(arr+i));
}
//printf("The 2nd element in the array is: %d", (*arr+1));
int i1 = 3;
int* px = &i1;
printf("\n%d", *px);
struct node root;
root.val = 13;
struct node left1;
struct node left2;
left1.val = 100;
left2.val = 2;
root.left = &left1;
root.right = &left2;
struct node curr = root;
while(curr.left != NULL){
printf("\nValue is: %d\n", curr.val);
curr = *curr.left;
}
char s[] = "Hi, my name is Aaron";
printf("\n%c\n", s[16]+3);
int one = modular(8, 104);
printf("\n%d\n", one);
point1.x = 1;
point1.y = -1;
printf("The y coordinate of point1 is: %d\n", point1.y);
struct point point3;
struct point point4 = {7, 12};
printf("The coordinates for point4 are %d and %d\n", point4.x, point4.y);
struct point aP = makePoint(10, 10);
printf("For this one our coordinates are %d\n", aP.x);
myRect.pt1 = makePoint(38, 38);
printf("The bottom left of our rectangle is %d\n", myRect.pt1);
int arr8[10];
arr8[0] = -4;
printf("Arr of %d is: %d.\n\n", 0, arr8[0]);
int arrAgain[] = {7, 4, -3, 0, -8, 11, 31, 12};
insertionSort(arrAgain, sizeof(arrAgain)/sizeof(arrAgain[0]));
for(int i = 0; i < sizeof(arrAgain)/sizeof(arrAgain[0]); i++){
printf("The %dth element of arrAgain is: %d\n", i, arrAgain[i]);
}
int* pointer1;
printf("Size here is: %d\n", sizeof(pointer1));
for(int i = 0; i < 5; i++){
printf("x");
}
}
I tried replacing the for-loop with other "Hello-World" (i.e. 'irrelevant') type expressions - which caused a change I was NOT expecting. I moved the loop around within main - which kept the seg-fault still. I tried restarting VSCode, I tried commenting out the for-loop (which had an effect). I would expect that the code would work the same with or without those 3 lines at the end, and if it does perform differently, why the difference appears in a section of the code multiple lines above this point.
Answers
The behavior you're experiencing is indeed unexpected and suggests there might be an issue with memory corruption or undefined behavior in your program. Let's analyze your code to try to identify the root cause.
Here's the portion of your code that's causing the segmentation fault:
int* pointer1;
printf("Size here is: %d\n", sizeof(pointer1));
for(int i = 0; i < 5; i++){
printf("x");
}
It's unlikely that this for-loop itself is causing the segmentation fault, as it's a simple loop that prints "x" five times. However, it's possible that it's exacerbating an existing issue.
Here are a few things you can try to debug and identify the problem:
-
Check Pointer Initialization: You've declared
int* pointer1;
but haven't initialized it. Make sure thatpointer1
is properly initialized before accessing its value. -
Check Memory Access: Ensure that you're not accessing memory locations that you shouldn't be. This could be happening elsewhere in your code and might be triggered by the addition of the for-loop.
-
Enable Debugging Tools: Use tools like Valgrind to detect memory errors or undefined behavior in your program. Valgrind can help identify issues such as reading from or writing to uninitialized memory, accessing freed memory, and other memory-related problems.
-
Reduce Code to Minimal Example: Try to create a minimal example that reproduces the issue. Remove unnecessary parts of your code while keeping the problem intact. This can help isolate the issue and make it easier to understand.
-
Review Pointer Usage: Review how you're using pointers throughout your code. Make sure that you're properly allocating and freeing memory, and that you're not dereferencing null pointers or accessing out-of-bounds memory.
By carefully reviewing your code and employing these debugging techniques, you should be able to identify the source of the segmentation fault. Once you've identified the problem, you can then work on fixing it. If you're still having trouble, feel free to provide more information, and I'll do my best to assist you further.