C语言(Cygwin环境)循环调用函数出现异常及段错误问题
Hey, I spot the issue right away! Let's break this down step by step:
核心问题:Static数组的持久化存储
Your someoneDidSomething() function uses a static char message[255]; variable. Here's the catch: static variables in C are initialized only once, and their memory persists for the entire lifetime of the program. That means every time you call strcat() on it, you're appending new text to the end of the previous string instead of starting fresh.
- On the first call, the static array is empty (default-initialized to all null bytes), so your string builds correctly.
- But in the loop? Each subsequent call keeps adding to the same array. Eventually, the string grows beyond the 255-byte limit of the array, causing a buffer overflow—and that's exactly what triggers the segmentation fault.
Fix 1: Reset the static array each time (simple approach)
The easiest fix is to clear the static array at the start of each function call. You can do this by setting the first character to a null terminator ('\0'), which tells strcat() to start appending from the beginning:
char* someoneDidSomething() { static char message[255]; // Reset the array to an empty string message[0] = '\0'; strcat(message, getPerson()); strcat(message, " "); strcat(message, getVerb()); strcat(message, " "); strcat(message, getSomething()); strcat(message, "."); return message; }
Fix 2: Use dynamic memory allocation (safer for longer strings)
If you want to avoid static variables entirely (they can lead to unexpected behavior in multi-threaded code, for example), you can use malloc() to allocate memory for each new string. Just remember to free the memory in your main loop to avoid leaks:
Modified someoneDidSomething():
#include <stdlib.h> // For malloc/free #include <stdio.h> // For perror char* someoneDidSomething() { // Allocate 255 bytes for the message char* message = malloc(255 * sizeof(char)); if (message == NULL) { perror("Failed to allocate memory"); exit(EXIT_FAILURE); } // Initialize to empty string message[0] = '\0'; strcat(message, getPerson()); strcat(message, " "); strcat(message, getVerb()); strcat(message, " "); strcat(message, getSomething()); strcat(message, "."); return message; }
Modified main():
void main () { for (int i = 0; i <= 500; i++) { char* message = someoneDidSomething(); printf("Because %s\n", message); free(message); // Don't forget to free the allocated memory! sleep(1); } }
Either fix will stop the string concatenation overflow and eliminate the segmentation fault. The first is simpler for your use case, while the second is more flexible if you ever need longer strings or thread-safe code.
内容的提问来源于stack exchange,提问作者Glen E. Renner

