I am trying to create a function which should return all arguments as a concatenated char array. Unfortunately, I get an ‘invalid pointer’ error while using the function. I’m new to C so maybe I’m wrong in using realloc in this way.
char* concat(int argc, ...) {
char* result;
va_list args;
va_start(args, argc);
int i;
for (i = 0; i < argc; i++) {
char* s = va_arg(args, char*);
int length = (result) ? strlen(result) : 1;
char* tmp = (char*)realloc(result, sizeof(char) * (strlen(s) + length - 1));
if (tmp == NULL) {
throw_error("Realloc failed in `concat`.");
}
result = tmp;
memcpy(&(result[length-1]), s, strlen(s));
printf("result: %s\n", s);
}
va_end(args);
return result;
}
The error message if it can help:
*** glibc detected *** ./pascc: realloc(): invalid pointer: 0x00000000006060c8 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x76bb6)[0x7f9953be8bb6]
/lib/x86_64-linux-gnu/libc.so.6(realloc+0x338)[0x7f9953beed58]
./pascc[0x401368]
./pascc[0x400f85]
./pascc[0x4019bb]
./pascc[0x403c49]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xff)[0x7f9953b90eff]
./pascc[0x400e29]
======= Memory map: ========
00400000-00406000 r-xp 00000000 08:05 2885504
To avoid memory leak, I read in an other thread that I shouldn’t realloc something itself like this:
result = (char*)realloc(result, sizeof(char) * (strlen(s) + length - 1));
So I’m trying to find the good way to do this. Some help would be appreciated.
You are
reallocing an uninitialized pointer.To use
reallocyou must either use a NULL pointer or a pointer that points to memory that was assigned bymalloc.