I'm trying to concat two strings, supposing the "dest" string hasn't enough space to add another one, so I'm using dynamic arrays to solve it.
The problem is a mremap_chunk error when trying to compile the code.
I don't know what I'm missing since the realloc call has all the right params place in.
Error:
malloc.c:2869: mremap_chunk: Assertion `((size + offset) & (GLRO (dl_pagesize) - 1)) == 0' failed.
Aborted (core dumped)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *strcatt(char *s1, char *s2)
{
int a = strlen(s1);
int b = strlen(s2);
int i, size_ab = a+b;
s1 = (char *) realloc (s1, size_ab*sizeof(char));
for(i=0; i<b; i++) {
s1[i+a]=s2[i];
}
s1[size_ab]='\0';
return s1;
}
int main()
{
char s1[]="12345";
char s2[]="qwerty";
strcatt(s1,s2);
printf("%s\n", s1);
return 0;
}
First, you are treating non-heap memory as heap memory, don't do that.
Second you're not including space for the terminator in the calculation.
Here are some more points:
str
, that's a reserved name space.size_t
, notint
.malloc()
in C.memcpy()
to copy blocks of memory when you know the size.const
.sizeof (char)
, that's always 1.Here's how I would write it, assuming the same logic:
You can not
realloc
orfree
a memory that is not allocated with a call tomalloc
or is notNULL
.From section 7.22.3.5. The realloc function in C11 draft
So,
s1 = (char *) realloc (s1, size_ab*sizeof(char));
is plainly wrong for your inputs (automatic arrays), never do that.And then there are many more problems which can be fixed with some help from a debugger.
The clang debugger gives a very clear error description:
Both of your arrays are initialized as string literals. Further on, your function tries to modify a string literal by reallocing it, which is wrong by C standard because you can't reallocate what you haven't allocated, and then copying the members of the second string literal to the "object" you intended to modify by misusing
realloc()
on a string literal.The code would work if you had dynamically defined a third string in which you would have summed the contents of both:
Please, also note that you don't cast the return of
malloc()
in C.