Hi.
Sooner or later I had to go into the depths of C. Today was the day I tried my first things with C. However, I am having a problem although I do not know what actually causes it.
The goal of the pogram is to combine the parameters into one char array, instead of having an array of char arrays. Eventually it needs to call another exe, in which it will measure the time it needs to execute (not implemented yet).
The problem is that the program always ends with an error, while the program does its job so far. I assume that there is a problem with allocating and freeing memory. I allocate memory at the function concatenate, but I never free that memory. Since I cannot free it inside the function itself (it is needed to return), I have made several attempts to make a pointer to the returned value but it all failed, hence free is marked as comment.
Does anyone have an idea what exactly causes this problem or can even solve the problem? The error is thrown at the moment before the main returns 0.
Thanks in advance.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
char* concatenate(int len, char** argv) {
char* concatArgv;
int i;
concatArgv = (char*)malloc(sizeof(argv) + 1);
strcpy(concatArgv, argv[0]);
if (len > 1) {
for (i = 1; i < len; i++) {
strcat(concatArgv, " ");
strcat(concatArgv, argv[i]);
}
}
return concatArgv;
}
int main(int argc, char** argv) {
clock_t start, finish;
char* str;
int i;
start = clock();
printf("Number of parameters: %i\n", argc);
for(i = 0; i < argc; i++) {
printf("%s\n", argv[i]);
}
str = concatenate(argc, argv);
finish = clock();
printf("%s\n", str);
printf("Execution time in seconds: %f\n", ((float)(finish - start))/CLOCKS_PER_SEC);
//free(str);
return 0;
}