I'm trying to implement a function that concatenate two strings, but I keep getting the same error. "pointer being realloc'd was not allocated" When I compiled the same code on a windows machine it worked, is it something that I'm missing? The code below is basically what I'm trying to do. main:
int main() {
int length = 4096;
char *string = malloc(length * sizeof(char));
createString(string, length);
realloc(string, 30);
return 0;
}
createString:
void createString(char * string, int length) {
char *copyAdress = string;
char *temp ="";
int counter2 = 0;
fflush(stdin);
fgets(string, length,stdin);
while(*string != EOF && *string != *temp ) {
string++;
counter++;
}
string = copyAdress;
realloc(string, (counter)*sizeof(char));
}
Thanks! Edit: I want createString to change the size of string to the length of the string that I get with fgets, while having the same address as the string that I sent in, so I can allocate more memory to it later when I want to add another string to it.
Let's work through this in order of execution.
fflush(stdin);
is undefined behaviour. If you really need to clear everything in the stdin you have to find another way (a loop for example). There are compilers/systems with a defined implementation but I would not count on it.
string++;
is superflous as you overwrite string
after the loop.
realloc(string, (counter)*sizeof(char));
should be
char *temp = realloc(string, (counter)*sizeof(char));
if (temp != NULL)
string = temp;
This way you get the pointer where your new string
is located, but I suggest you read the refecerence for realloc
. In essence you do not know if it has been moved and the old address might be invalid from that point on. So dereferencing it is also undefined behaviour.
After this you would have to return the new address of string
or pass the address of the pointer to your function.
The same problem repeats with the second realloc
. You only got to know your first call was wrong, because the second call noticed that you do not have valid data in what you thought would be your string
.
In regards to your comment: It is not possible to use realloc
and to be sure that the reallocated memory is in the same place as before.