C语言中使用malloc返回数组指针时出现Segmentation error问题求助
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
Type Mismatch Disaster
You declaredarrayas anint*(an array of integers), but you're assigningchar*values (the pointers returned bystrtok) to its elements. When you later try to printarray[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.Dangling Pointers from Local Memory
Thebuffervariable is a local array inside thedata()function. Whendata()finishes executing, the system reclaims this memory. Butstrtokreturns pointers to positions insidebuffer—so when you store those pointers in your array and return it tomain(), 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.Potential Array Overflow
You allocated space for only 4 integers, but if the user enters more than 4 comma-separated values,longiwill 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
strtokresult into its ownmalloc'd memory, we avoid relying on the localbufferthat gets destroyed whendata()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 becausearr[i]is a validchar*pointing to allocated string memory.
内容的提问来源于stack exchange,提问作者Abner

