I want to be able to pass a string into a function that takes the array of characters that form the string and change it to the other string provided. The issue is that I get an error telling me that the pointer being reallocated (using realloc) has not been allocated (using malloc).
I made sure that the pointer being used in the function is the same as the one being used in the main routine as shown by the pointer print statements. I have tried not passing in the string char array address but just itself. None of these have worked.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void change(char **old_string, char *new_string);
int main(int argc, char *argv[]) {
if (argc == 2) {
char *string;
string = malloc((strlen(argv[1]) + 1) * sizeof(char)); // + 1 for \0
string = argv[1];
printf("Pointer outside Function: %p\n", string);
printf("String Before: %s\n", string);
change(&string, "New String");
printf("String After: %s\n", string);
} else {
printf("Please enter a string to have changed.\n");
}
return 0;
}
void change(char **old_string, char *new_string) {
printf("Pointer in Function: %p\n", *old_string);
*old_string = realloc(*old_string, (strlen(new_string) + 1) * sizeof(char)); // + 1 for \0
strcpy(*old_string, new_string);
}
Current results when run are:
Pointer outside Function: 0x7ffeed590c88 String Before: test Pointer in Function: 0x7ffeed590c88 a.out(20309,0x111496d40) malloc: * error for object 0x7ffeed590c88: pointer being realloc'd was not allocated a.out(20309,0x111496d40) malloc: * set a breakpoint in malloc_error_break to debug Abort trap: 6
What should happen:
Two strings should be provided to the function. The first argument being the pointer to chars and with the second being a string literal. The pointer to chars provided should be useable in the main routine.
string = argv[1];You are assigning pointer to something that was not mallocatedsizeof(char)is guaranteed to be equal to one.string = malloc ...and the next onestring = something else.