EDIT: I have changed my program according to suggestions people have made but I am unable to fix memory leaks. Also, I need to free them without using argc, so i need to somehow keep track of the array length so I marked the last element as null.
Currently I'm writing a C program that copies the command line arguments into a dynamically allocated array. My code looks like:
char **array;
int j;
array = malloc(sizeof(char*) * (argc + 1));
int i;
int index = 0;
for(i = 0; i < (argc); i++){
int length = strlen(*(argv + i));
array[i] = malloc((length + 1) * sizeof(char));
// Cycle through all the chars and copy them in one by one
for(j = 0; j <= length; j++){
array[i][j] = toupper(argv[i][j]);
}
}
array[i + 1] = NULL;
return array;
Later, I try to free the memory:
char** array_copy = array;
while(*array_copy != NULL){
free(*array_copy++);
}
free(*array_copy) // free the null at the end
free(array);
However, I still get memory leaks. I'm not quite sure what I'm doing wrong. If anyone could give me tips that would be great.
Thank!