i wanted to find the duplicates present in an array of pointers.the code is shown below.when i run this application it is gining segmentation fault.But when i extract this f
I think this part would be the root of the problem:
while ((dit = readdir(dip)) != NULL)
{
condition_var = dit->name;
a[i] = condition_var;
i++;
}
I am not sure about how readdir() works but I would guess that every time it will return a temporal structure pointer to dit. a[i] saves condition_var as the pointer to the name. It is possible that later another call to readdir() is made and uses the exact the same mem space to return the temporal structure, overwriting the mem space that a previous condition_var pointing to.
I would suggest a safer way to do this part, which may be a little more complex, though.
while ((dit = readdir(dip)) != NULL)
{
int len = strlen(dit->name);
condition_var = malloc(len+1);
memncpy(condition_var, dit->name, len+1);
//condition_var = dit->name;
a[i] = condition_var;
i++;
}
Remember to free every mem block that you malloced, at the end of the program. (Or you can just leave all these to OS to collect the mem--not recommended). The code should be like this:
int j; // use another loop indicator if you already declared j for other uses.
for(j = 0; j