使用argc和argv时出现realloc(): invalid pointer错误的解决求助
Hey there! Let's figure out why you're hitting that realloc(): invalid pointer error when switching to argc/argv for your grep-like program. This issue almost always boils down to mismanaging memory pointers—especially when dealing with the system-provided argv array.
Common Causes of the Error
First, let's clarify a critical point: the strings in argv are allocated and managed by the operating system. You cannot call realloc (or free) directly on these pointers. If your code tries to reallocate memory that's not owned by your program (like argv[1] or argv[2]), you'll trigger that invalid pointer error immediately.
Another possible culprit is mishandling dynamic memory when reading file lines. For example, if you initialize a line pointer to a random value (instead of NULL) before using realloc or getline, you'll be trying to reallocate a non-heap pointer.
Fixing the Issue
Let's walk through a corrected version of your program that avoids these pitfalls, with explanations of key changes:
#include <stdio.h> #include <string.h> #include <stdlib.h> // Simplified search function (returns 1 if str2 is found in str1, 0 otherwise) int searchString(char *str1, char *str2) { return strstr(str1, str2) != NULL; } void searchInFile(char *filename, char *str) { FILE *f = fopen(filename, "r"); if (!f) { perror(filename); // Print error if file can't be opened return; } char *line = NULL; // Initialize line pointer to NULL (critical for getline/realloc) size_t len = 0; ssize_t read_len; // Use getline to safely read lines (it handles realloc automatically) while ((read_len = getline(&line, &len, f)) != -1) { if (searchString(line, str)) { printf("%s: %s", filename, line); } } free(line); // Clean up the memory allocated by getline fclose(f); } int main(int argc, char *argv[]) { // Validate input arguments if (argc < 3) { fprintf(stderr, "Usage: %s <search-string> <file1> [file2...]\n", argv[0]); exit(EXIT_FAILURE); } // Copy the search string to our own heap memory (avoids touching argv's pointers) char *search_str = strdup(argv[1]); if (!search_str) { perror("Failed to allocate memory for search string"); exit(EXIT_FAILURE); } // Iterate over all provided files for (int i = 2; i < argc; i++) { searchInFile(argv[i], search_str); } free(search_str); // Clean up our allocated memory return EXIT_SUCCESS; }
Key Fixes Explained
Avoid modifying
argvpointers:
We usestrdupto copy the search string fromargv[1]into our own heap-allocated memory. This gives us full ownership of the string, so we can safely modify or reallocate it later if needed (without messing with system-managed memory).Properly initialize dynamic pointers:
InsearchInFile, we initializelinetoNULL. Whengetlineis called with aNULLpointer, it automatically allocates memory for the line—and reallocates it if the line is longer than the current buffer. This eliminates invalid pointer issues from uninitialized memory.Clean up allocated memory:
We alwaysfreememory we've allocated (likesearch_strand thelinepointer fromgetline) to avoid leaks, which also helps prevent accidental reuse of freed pointers (another common cause of realloc errors).
Quick Checks for Your Original Code
If you want to debug your existing code, look for these red flags:
- Did you call
reallocdirectly on anyargvelement (e.g.,realloc(argv[1], ...))? - Did you initialize a pointer to a stack variable or uninitialized value before calling
realloc? - Did you forget to initialize a pointer to
NULLbefore using it withreallocorgetline?
内容的提问来源于stack exchange,提问作者Alfonso Jiménez

