Malloc is used for dynamic memory allocation. However, this code doesn't use malloc, but is dynamic. In what case would I use malloc? Or is this code doing something really bad?
Sometimes, I see this style of coding in answers on Leetcode.
#include <string.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
int len = strlen(argv[1]);
char test[len+1];
memset(test,0,len+1);
strcpy(test,argv[1]);
printf("%s\n",test);
return 0;
}
so why would I do this instead?
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
int len = strlen(argv[1]);
char *test = calloc(len+1,sizeof(char));
strcpy(test,argv[1]);
printf("%s\n",test);
free(test);
return 0;
}