Reputation: 103
I am trying a make a function that appned a string after another string. I am witnessing the following error. Please help. * glibc detected ./a.out: realloc(): invalid old size: 0x00007fff7af0d450 **
// The following code concatenates the orignal string into the another
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void strcatstring(char *str,char *newstr)
{
int m=strlen(str);
int n=strlen(newstr);
newstr=(char *)realloc(newstr,10*sizeof(char));
char *newstr1=(char *)malloc(10*sizeof(char));
newstr1=newstr;
while(*newstr!='\0')
{
++newstr;
}
while(*str!='\0')
{
*newstr=*str;
++newstr;
++str;
}
printf("%s",newstr1);
}
int main()
{
int n=6;char *str;char str1[10];
str1[0]='y';
str1[1]='u';
str=(char *)malloc(n*sizeof(char));
printf("\nEnter the string\n");
scanf("%s",str);
puts(str);
strcatstring(str,str1);
return 0;
}
Upvotes: 0
Views: 86
Reputation: 608
Your str1 is an array, which is allocated on the stack. realloc()
has to be used on a pointer whose space is allocated on the heap.
Upvotes: 0
Reputation: 409482
The problem is that you try to reallocate memory that is not allocated (in the way realloc
wants it) in the first place.
You declare str1
as an array in the main
function, this memory will be allocated on the stack by the compiler and not on the heap. The realloc
function only can reallocate memory allocated on the heap, either by malloc
, calloc
or an earlier realloc
call.
And if the realloc
call would have worked, then you have a memory leak, as you allocate memory and assign it to newstr1
and in the next line overwrite the newstr1
pointer with the newstr
pointer.
And you should really not allocate a fixed size, remember that you append one string of size m
to a string of size n
. Think about what would happen if m + n
is larger than 9. Which leads to the next problem, that you don't terminate the resulting string as you don't copy the terminating '\0'
character.
Upvotes: 2
Reputation: 22311
str1
you are using may not be ending with '\0'. You have to manually put that character at the end.
You can not realloc memory allocated on the stack. str1
is allocated on the stack.
Proper strcat()
has the arguments in other order. Destination comes first.
Your naming convention is terrible. str
? newstr
? How about source
and destination
. Moreover, m
and n
say nothing. Why not sourceLen
and destinationLen
?
After completing your loop in strcatstring()
you do not put the '\0' character at the end. You will most probably get memory errors by using that string.
Upvotes: 0
Reputation: 867
Try to pass pointer to a pointer while calling as follows
strcatstring(str,&newstr);
Upvotes: 0