排查最短路径C语言代码中Segmentation Fault 11错误原因
Hey there, let's dig into that segmentation fault you're hitting. First off, I notice your code snippet cuts off mid-way through the strrev function—there's a char... hanging at the end. But even with what's visible, let's break down the most likely culprits for a segfault in this kind of code, plus fixes to try:
1. Incomplete strrev Implementation
Your strrev function only sets up the start/end pointers but doesn't include the character-swapping logic. If you call this unfinished function later, it'll almost certainly cause invalid memory access. Here's the complete, safe version:
char * strrev (char *str) { if (!str) { fprintf (stderr, "%s() Error: invalid string\n", __func__); return NULL; } char *begin = str; char *end = str + strlen (str) - 1; char temp; // Swap characters from start and end moving inward while (begin < end) { temp = *begin; *begin = *end; *end = temp; begin++; end--; } return str; }
Important note: This function only works with modifiable strings (like stack-allocated char arrays). If you pass a string literal (e.g., char *s = "hello";), modifying it is undefined behavior and will likely trigger a segfault.
2. Curses Library Misuse
You're including curses.h but if your code doesn't properly initialize or clean up the curses library, it can cause terminal-related crashes or memory errors. Make sure your main function includes these critical steps:
int main() { // Initialize curses before using any of its functions initscr(); // ... rest of your shortest path algorithm code ... // Clean up curses resources before exiting endwin(); return 0; }
3. Array/Buffer Overflow
You defined int size = 20;—if you use this to create arrays (e.g., int graph[size][size];) and then access indices beyond the valid range (like graph[20][0], since arrays are 0-indexed), that's a classic segfault trigger. Double-check all array accesses to ensure they stay within 0 to size-1.
4. Null Pointer Dereferencing
If any part of your code tries to access memory via a NULL pointer (e.g., using malloc and not checking if it returned NULL before using the pointer), you'll get a segfault. For dynamic allocations, always add a check:
int *dist = malloc(size * sizeof(int)); if (!dist) { fprintf(stderr, "Malloc failed for distance array\n"); exit(EXIT_FAILURE); }
5. Tools to Pinpoint Exact Issues
If you're still stuck, use valgrind to get a precise line number for the invalid memory access:
valgrind ./your_program_name
It'll tell you exactly where your code is trying to access memory it shouldn't, which is invaluable for debugging segfaults.
If you can share the full, uncut version of your code, we can narrow this down even further—but these fixes should cover most common issues in a shortest path algorithm implementation.
内容的提问来源于stack exchange,提问作者Clicker

