I was trying to figure a way to expand a string capacity without using realloc
. for example what is the major difference between this code:
void insert(char *dest, char *src, int pos){
char *temp = malloc(strlen(dest)+strlen(src)+1);
/*
malloc failure handling
*/
strcpy(temp,dest);
//rest of code
}
and:
void insert(char *dest, char *src, int pos){
char *temp =(char*)realloc(dest,strlen(dest)+strlen(src)+1);
/*
realloc failure handling
*/
dest = temp;
//rest of code
}
or is there any better way to do it?
note that both src
and dest
are intialized using malloc
.
Doing malloc --> memcpy --> free
in fact is what realloc
conceptually does, just only somewhat optimised.
And because of this optimisation this question
what is the major difference between this code
can be answered by saying, that the former could be faster and more efficient in terms of memory fragmentation.
How to expand a string capacity without using realloc()?
If VLA's* are available (which were not before C99 and perhaps in C11 and never in C++) and you know the maximum size of input and this size would never lead to a stack overflow then and only then you could do:
#include <stdio.h>
#include <string.h>
...
char s1[] = "123";
char s2[] = "456";
char s3[] = "789";
char s[strlen(s1) + strlen(s2) + strlen(s3) + 1];
strcpy(s, s1);
strcat(s, s2);
strcat(s, s3);
puts(s);
and will see
123456789
All in all if starting playing with malloc()
there is no reason to not as well turn to its cousin realloc()
.