I have written a program where it reads some filenames and a word from command line arguments. The first argument will be a word and remaining will be filenames. It fills a structure that I have defined.
However for small arguments, the program works correctly but for large ones malloc
gives corrupted top size error.
Below is just initial code of the program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME_LIM 256
#define WORD_LIM 256
struct data {
char filename[FILENAME_LIM];
char word[WORD_LIM];
};
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("usage: ./a.out word filename1 filename2 filename3 filename4 filename5 ...\n");
exit(EXIT_FAILURE);
}
char word[WORD_LIM];
strcpy(word, argv[1]);
int files = argc - 2;
struct data *dataarray = (struct data *)malloc(sizeof(sizeof(struct data) * files));
if (!(dataarray)) {
perror("malloc");
exit(EXIT_FAILURE);
}
for (int i = 0; i < files; i++) {
strcpy(dataarray[i].filename, argv[i + 2]);
for (int ii = 0; ii < strlen(dataarray[i].filename) + 1; ii++) {
printf("filename[%d] = %c (%d), argv[%d] = %d\n",
i, dataarray[i].filename[ii], dataarray[i].filename[ii],
i, argv[i + 2][ii]);
}
}
return 0;
}
I tried everything, but when I give some large filename in argv
such as "../../../C Programs/chess.c"
, malloc
yields an error. I want to know what is making corrupted top size.