KaramJaber
KaramJaber

Reputation: 893

C - Initializing an array of pointers

I am trying to initialize an array of pointers but when i try to print it in the main it don't work, It shows an segmentation fault but if i try to print it in the same method it do print

here is my code

typedef struct File
{
    char fileName[Max_FILE_NAME_LENGTH];
    char *listOfFiles[];
}File;

File dependencies[MAXIMUM_FILES];

void findListOfFiles(char *line, int i, int currDepend)
{
int idx=0,numOfFiles=0;;
while(line[i]!='\n')
{
    char *name=(char *)malloc(65*sizeof(char));
    while(line[i]!=',' && line[i]!='\n')
    {
        name[idx]=line[i];
        i++;
        idx++;
    }
    name[idx]='\0';
    dependencies[currDepend].listOfFiles[numOfFiles]=name;
    printf("%s+", dependencies[currDepend].listOfFiles[numOfFiles]);
    if(line[i]=='\n')
    {
        if(name){
            free(name);
            name=NULL;
        }
        break;
    }
    if(name){
        free(name);
        name=NULL;
    }
    numOfFiles++;
    i++;
    idx=0;
}
}

Upvotes: 0

Views: 678

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

You never actually allocate space for the listOfFiles member anywhere. This means that this array is, essentially, of size zero so all writing to any entry in it will be out of bounds.

If you want dependencies to be a global variable, you have to either set a fixed size for the listOfFiles array, or make it a pointer-to-pointer and allocate/reallocate when needed.

Also, after you assign the pointer name to the array, you then free this allocated memory, meaning the pointer now in the array points to free'd memory.

Upvotes: 1

Related Questions