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

C语言中使用malloc返回数组指针时出现Segmentation error问题求助

Why You're Getting a Segmentation Fault & How to Fix It

Hey there! Let's break down what's going wrong here and fix it step by step—no need to worry about asking "basic" questions, we all start somewhere.

Let's List the Critical Issues in Your Code

  1. Type Mismatch Disaster
    You declared array as an int* (an array of integers), but you're assigning char* values (the pointers returned by strtok) to its elements. When you later try to print array[0] with %s, the program treats that integer value as a memory address for a string—this is a guaranteed recipe for a segmentation fault, since that "address" is almost certainly invalid.

  2. Dangling Pointers from Local Memory
    The buffer variable is a local array inside the data() function. When data() finishes executing, the system reclaims this memory. But strtok returns pointers to positions inside buffer—so when you store those pointers in your array and return it to main(), you're left with dangling pointers (pointing to memory that's no longer yours). Accessing that memory is undefined behavior, which usually leads to a segfault.

  3. Potential Array Overflow
    You allocated space for only 4 integers, but if the user enters more than 4 comma-separated values, longi will keep incrementing and you'll write past the end of your allocated array. This corrupts heap memory and can cause all sorts of weird errors, including segfaults.

Here's the Fixed Code

First, we need to store strings (not integers) since you're working with "A"/"F" input. We'll use a char** (an array of string pointers) and allocate separate memory for each string to avoid dangling pointers.

Modified data() Function

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char** data() {
    int count = 0;
    // Start with space for 4 strings, we'll expand if needed
    char** array = malloc(4 * sizeof(char*));
    if (!array) { // Always check if malloc succeeds!
        perror("Failed to allocate array");
        return NULL;
    }

    char buffer[1024];
    char* aux;

    printf("Enter approved(A) or failed(F) separated by commas: \n");
    fgets(buffer, sizeof(buffer), stdin);

    // Remove the newline character added by fgets
    buffer[strcspn(buffer, "\n")] = '\0';

    aux = strtok(buffer, ",");
    while (aux != NULL) {
        // Allocate memory for the current string (+1 for null terminator)
        array[count] = malloc(strlen(aux) + 1);
        if (!array[count]) {
            perror("Failed to allocate string");
            // Clean up already allocated memory to avoid leaks
            for (int i = 0; i < count; i++) {
                free(array[i]);
            }
            free(array);
            return NULL;
        }
        // Copy the string into our allocated memory
        strcpy(array[count], aux);
        count++;

        // Expand the array if we've filled our current allocation
        if (count % 4 == 0) {
            char** temp = realloc(array, (count + 4) * sizeof(char*));
            if (!temp) {
                perror("Failed to expand array");
                // Clean up before exiting
                for (int i = 0; i < count; i++) {
                    free(array[i]);
                }
                free(array);
                return NULL;
            }
            array = temp;
        }

        aux = strtok(NULL, ",");
    }

    // Optional: Shrink the array to exactly the number of elements we need
    char** final_array = realloc(array, (count + 1) * sizeof(char*));
    if (final_array) {
        array = final_array;
    }
    // Add a NULL pointer at the end to mark the array's end
    array[count] = NULL;

    return array;
}

Modified main() Function

int main() {
    char** arr = data();
    if (!arr) {
        return 1;
    }

    // Iterate through the array and print each element
    for (int i = 0; arr[i] != NULL; i++) {
        printf("Entry %d: %s\n", i+1, arr[i]);
        free(arr[i]); // Free each individual string
    }
    free(arr); // Free the array itself

    return 0;
}

Key Fixes Explained

  • Switched to char**: This lets us store an array of string pointers, which matches your input type.
  • Allocated per-string memory: By copying each strtok result into its own malloc'd memory, we avoid relying on the local buffer that gets destroyed when data() exits.
  • Dynamic array expansion: The array grows automatically if the user enters more than 4 values, preventing overflow.
  • Memory cleanup: We added checks to clean up allocated memory if something goes wrong, and main() frees all memory to avoid leaks.
  • Removed type mismatches: Now printf("%s", arr[i]) works correctly because arr[i] is a valid char* pointing to allocated string memory.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:37:32