I was trying to implement a simple function that can concatenate any number of strings passed to it. My call to realloc fails. Is it something to do with the fact that the string arguments that i pass to the function are stored in data segment where as realloc looks to allocate memory from the heap ? This is just an idea i have. I’m a beginner so please excuse if it seems stupid. How can i make this function run ?
//Program to implement a function that can concatenate any number of argumnets
#include<stdio.h>
#include<stdarg.h>
#include<string.h>
#include<stdlib.h>
char *mstrcat(char *first, ...);
int main(int argc, int **argv){
char *s;
s=mstrcat("I ","Love ","Stack","Overflow");
printf("%s\n",s);
}
char *mstrcat(char *first, ...){
char *s=first,*p;
int len=0; // stores the length of the string as it grows
len=strlen(s);
va_list aptr; // creates a pointer to the unnamed argument list
va_start(aptr,first); // initialise aptr to the first unnamed argument
if(aptr==NULL){
return s;
}
while((p=va_arg(aptr,char *))!=NULL){ // till there are no more arguments to process
len+=strlen(p);
if((s=(char *)realloc(s,len+1))!=NULL){
strcat(s,p);
}
else{
printf("Failed to concatenate\n");
return first;
}
}
return s;
}
Your code has an Undefined Behavior. The standard mandates that the pointer being passed to
reallocshould exactly match the pointer which was allocated dynamic memory using a memory management function. Memory management functions specified by the standard are:aligned_alloc,calloc,malloc, andrealloc.The pointer you are passing to
realloc()was not returned by any of these and hence the Undefined Behavior.Reference:
c99 standard: 7.22.3.5 The realloc function
Synopsis: #1
#3