类Unix系统中C程序出现Segmentation fault (core dumped)问题求助
strcpy in Unix C Programs Hey there! Let's break down this segmentation fault issue tied to strcpy—it's a super common pitfall, so we'll get this sorted quickly.
Why This Happens (Likely Root Causes)
Even though you've declared con and count stays under 30, here are the most probable issues with that problematic strcpy line:
conisn't pointing to valid, writable memory
If you declaredconas a raw pointer likechar *con;without allocating memory for it,strcpywill attempt to write to a random garbage address. Unix systems strictly block unauthorized memory access, which triggers the "Segmentation fault (core dumped)" error. A declared pointer doesn't automatically get a valid memory space—you have to explicitly assign it one.The source string isn't a proper C-style string
If the string you're copying doesn't end with a null terminator (\0),strcpywill keep reading memory until it finds one, potentially crossing into invalid memory regions. That said, since removing thestrcpyline fixes the issue, this is less likely than the first problem.
Fixes to Resolve the Issue
Let's address the most common scenario first, then cover safer alternatives:
1. Ensure con has valid writable memory
Choose one of these approaches based on your needs:
Stack-allocated array (simple, for small fixed-size strings)
If you don't need the string to outlive the current function, declare con as a stack array:
char con[30]; // Allocates 30 bytes on the stack—plenty for count < 30 (plus null terminator)
Note: Stack arrays hold garbage values by default, but they're still valid, writable memory for strcpy to use.
Heap-allocated memory (for dynamic size or longer lifetimes)
If you need the string to persist beyond the function scope, use malloc:
#include <stdlib.h> #include <stdio.h> // ... later in your code ... char *con = malloc(30 * sizeof(char)); if (con == NULL) { // Handle memory allocation failure (critical to avoid undefined behavior) perror("Failed to allocate memory for con"); exit(EXIT_FAILURE); } // When you're done with con, free the memory to avoid leaks // free(con);
2. Use a safer alternative to strcpy
Even if you fix the memory issue, strcpy is risky because it doesn't check for buffer overflow. For better safety, use strncpy (and always manually add the null terminator):
// Copy up to 29 characters (leaving space for the null terminator) strncpy(con, your_source_string, 29); // Explicitly add the null terminator—strncpy won't do this if the source is shorter than 29 con[29] = '\0';
This ensures you never write beyond the bounds of con's allocated memory.
Final Check
Double-check that your source string is properly null-terminated too. If you're building the source string manually (e.g., from a character array), make sure you set the count-th index to '\0' before copying.
内容的提问来源于stack exchange,提问作者Eileen

