C语言魔法方阵程序出现Segmentation fault (core dumped)错误及输出异常的求助
Hey there! Let's break down the issues in your code one by one—both the segmentation fault and the messy output come from a few key mistakes in logic, initialization, and syntax.
1. Invalid Check for Unfilled Positions (and Uninitialized Array)
Your square array is a local stack variable, which means it's filled with random garbage values by default. Using if(square[cord_y][cord_x] == NULL) to check if a spot is empty is totally wrong:
NULLis for pointer comparisons, but your array holdsintvalues—this is a type mismatch that leads to unpredictable behavior.- Fix: First initialize the entire array to
0(since you're filling it with positive integers from 1 tosize*size), then check if a position is0to see if it's empty.
Add this right after declaring the array:
for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { square[i][j] = 0; } }
2. Broken Coordinate Boundary Handling (Root of Segmentation Fault)
Your current code uses cord_x -= size+1 and cord_y -= size+1 to fix out-of-bounds coordinates, which turns valid positive indices into negative numbers (e.g., for size=3, cord_x=3 becomes -1). Accessing square[...][-1] is an illegal memory access—this is exactly what causes the segmentation fault.
Fix this with simple boundary checks that wrap coordinates back into the array:
- If moving up takes
cord_ybelow 0, set it to the last row (size-1) - If moving right takes
cord_xbeyondsize-1, set it to 0
3. Wrong Movement Direction (Core Logic Error)
Your algorithm says to move up one row, right one column for the next number, but your code does cord_y +=1 (down one row) and cord_x +=1 (right one column). This completely reverses your vertical movement, leading to all positions being wrong.
4. Unimplemented "Fall Back Down" Logic
Your else { continue; } just skips filling the current number instead of handling the algorithm's rule: if the next position is already filled, place the number directly below the current one. You need to adjust the coordinates to move down one row in this case.
5. Broken show Function
- The function uses old C syntax that can confuse modern compilers—declare it as
void(since it doesn't return anything) beforemain(). - You swapped
iandjin the print loop, which prints columns instead of rows. Fix it toarray[i][j]to print row by row.
Fixed Code Example
Here's the code with all these issues resolved:
#include<stdio.h> // Declare show function before main void show(int s, int array[s][s]); int main() { int size, i; printf("Enter size of square: "); scanf("%d",&size); // Magic square (Siamese method) only works for odd sizes if (size % 2 == 0) { printf("This algorithm works best with odd-sized squares!\n"); return 1; } int square[size][size]; // Initialize array to 0 (empty marker) for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { square[i][j] = 0; } } // Start at top row, middle column int cord_y = 0; int cord_x = size / 2; for(i=1; i <= size*size; i++) { // Fill current position square[cord_y][cord_x] = i; // Calculate next position: up 1, right 1 int next_y = cord_y - 1; int next_x = cord_x + 1; // Wrap around boundaries if (next_y < 0) next_y = size - 1; if (next_x >= size) next_x = 0; // If next position is filled, move down instead if (square[next_y][next_x] != 0) { next_y = cord_y + 1; next_x = cord_x; // Wrap down boundary just in case if (next_y >= size) next_y = 0; } // Update coordinates for next iteration cord_y = next_y; cord_x = next_x; // Print current state show(square, size); printf("\n"); } return 0; } void show(int s, int array[s][s]) { int i,j; for(i=0; i < s; i++) { for(j=0; j < s; j++) { printf("%d ", array[i][j]); } printf("\n"); // New line after each row } }
Why the Segmentation Fault Happened
The main culprit was your broken boundary handling, which created negative array indices. Accessing memory outside the array's bounds (like square[0][-1]) triggers a stack memory access error, hence the "Segmentation fault (core dumped)" message.
内容的提问来源于stack exchange,提问作者Saphereye

