0

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;
}
}
1
  • Is listOfFiles properly allocated? Commented Nov 10, 2013 at 19:54

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

now after i put the array of size 100 and, when i tried to print it it prints nothing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.