S
Shriramana Sharma
Hello. I am not a professional programmer and only program now and then. So please forgive me if my question sounds silly or naive.
I am trying to find out how to dynamically lengthen a string while concatenating in C, as it is easily possible to do so in C++ or Python (two other languages I have used).
I patched up the following code:
But it aborts with an error saying: "./strappend: realloc(): invalid pointer: 0x000000000040073c ***". No matter how many times I execute it that hex number remains the same.
Can anyone kindly point me to what I am doing wrong with realloc? I have never really used malloc/realloc stuff so I am probably botching things up somewhere but I'm not sure where.
Thanks!
I am trying to find out how to dynamically lengthen a string while concatenating in C, as it is easily possible to do so in C++ or Python (two other languages I have used).
I patched up the following code:
Code:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
void strappend ( char * a, char * b )
{
a = ( char * ) realloc ( a, strlen ( a ) + strlen ( b ) ) ;
strcat ( a, b ) ;
}
void main ( void )
{
char * name = "my name is" ;
strappend ( name, " this or " ) ;
strappend ( name, "that." ) ;
printf ( "%s\n", name ) ;
}
But it aborts with an error saying: "./strappend: realloc(): invalid pointer: 0x000000000040073c ***". No matter how many times I execute it that hex number remains the same.
Can anyone kindly point me to what I am doing wrong with realloc? I have never really used malloc/realloc stuff so I am probably botching things up somewhere but I'm not sure where.
Thanks!