You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言指针实现字符串拷贝出现段错误,求故障定位与修复方案

Fixing Segmentation Fault in Your C String Copy Code

Hey there! I totally get how frustrating it is to stare at code for hours and not spot the issue—let's break this down together.

The Root Cause of the Segmentation Fault

The problem lies in how you're declaring your strings:

char *str1 = "avanti";
char *str2 = "ujj";

When you assign a string literal to a char* pointer like this, the string is stored in read-only memory (the program's data segment). Any attempt to modify this memory (which your copy function is definitely doing when it tries to write one string into the other) will trigger a segmentation fault—your OS is stopping you from writing to protected memory.

How to Fix It

You need to make sure your target string lives in writable memory. Here are two solid approaches:

Approach 1: Use a Character Array

Arrays allocated on the stack are writable by default. Just declare your target string as an array large enough to hold the source string plus the null terminator (\0):

#include<stdio.h>

char *copy(char* dest, char* src);

int main() {
    // Declare str1 as a writable array with enough space
    char str1[10] = ""; // Empty array, or initialize with a default value
    char *str2 = "ujj"; // str2 can stay as a read-only literal since we're only reading from it
    
    copy(str1, str2);
    printf("Copied string: %s\n", str1); // Now this will output correctly
    
    return 0;
}

char *copy(char* dest, char* src) {
    char *temp = dest;
    // Copy each character until we hit the null terminator
    while (*src != '\0') {
        *dest++ = *src++;
    }
    *dest = '\0'; // Don't forget to add the null terminator!
    return temp;
}

Approach 2: Allocate Heap Memory with malloc

If you need the string to outlive the current function (or just prefer using pointers), use malloc to allocate writable memory on the heap. Just remember to free it when you're done to avoid memory leaks:

#include<stdio.h>
#include<stdlib.h> // For malloc/free
#include<string.h> // For strlen

char *copy(char* dest, char* src);

int main() {
    char *str2 = "ujj";
    // Allocate enough memory for the source string + null terminator
    char *str1 = malloc(strlen(str2) + 1);
    if (str1 == NULL) { // Always check if malloc succeeded!
        printf("Memory allocation failed\n");
        return 1;
    }
    
    copy(str1, str2);
    printf("Copied string: %s\n", str1);
    
    free(str1); // Clean up the allocated memory
    return 0;
}

char *copy(char* dest, char* src) {
    char *temp = dest;
    while (*src) {
        *dest++ = *src++;
    }
    *dest = '\0';
    return temp;
}

Key Takeaways to Remember

  • String literals are read-only: Never try to modify a string assigned directly to a char* pointer like char* ptr = "hello".
  • Writable memory options: Use stack-allocated character arrays or heap-allocated memory (via malloc) when you need to modify a string.
  • Always add the null terminator: Your copy function must end with *dest = '\0' to ensure the result is a valid C string.

内容的提问来源于stack exchange,提问作者Guru Rai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:42:40