Reputation: 191
I want to iterate through argv and copy the relevant information (starting at index 2) into a 2D char-array with the segment shown below.
typedef struct
{
char *source;
char **dict;
unsigned int size_of_dict;
} t_char_cluster;
...
int main(int argc, char** argv)){
t_char_cluster data;
data.dict = malloc(argc - 2);
data.source = argv[1];
data.size_of_dict = 0;
for (unsigned i = 2; i < argc; i++) {
data.dict[i - 2] = malloc(strlen(argv[i]));
strcpy(data.dict[i - 2], argv[i]);
data.size_of_dict++;
printf(" dict[0] at i = %d : %s \n", i, data.dict[0]);
}
}
This works perfectly until the 4th iteration (i starts at 2). After that, the 1st string (index 0) in the char array is getting corrupted. So the ouput of the printf statement looks as follows:
dict[0] at i = 2 : foo
dict[0] at i = 3 : foo
dict[0] at i = 4 : foo
dict[0] at i = 5 : foo
dict[0] at i = 6 : P�Te�U
...
dict[1] at i = 15 : P�Te�U
As I found out through debugging,dict[0]
is getting corrupted after the malloc()
call in the 4th iteration.
Upvotes: 0
Views: 70
Reputation: 1236
Your allocation data.dict = malloc(argc - 2)
is incorrect. Since you want to create an array of (argc-2)
char*
you should initizalize it with malloc((argc-2)*sizeof(char*));
.
Additionally, your inner allocation is also incorrect, you should use data.dict[i - 2] = malloc(strlen(argv[i])+1);
to give one extra element to store the final \0
.
Next time, you can detect easily these bad access using a tool such as valgrind
.
Edit: as pointed out by Jabberwocky, your main prototype is also incorrect, you should use int main(int argc, char** argv)
instead.
Upvotes: 2