jeudi 3 septembre 2015

Memory not allocated Second time - realloc err

I am writing function which can store multiple Files and data in it. For That I am using struct double pointer.

struct file{
    char *filename;
    int fileid;
    char *filelist;
    struct cmd** c1;
    int cmdcnt;
};

...
///
...
struct file** add_file(struct file** rptr,char *name,int filecount) {


    //*rptr = (struct rptr*)realloc(*rptr,24*filecount);

    rptr[filecount - 1]->filename = (char *)malloc(10 * sizeof(char *));
    rptr[filecount - 1]->filename = strdup(name);
    rptr[filecount - 1]->fileid = filecount;

    return rptr;
}
;
;
;
;
;
//
//
....in Main...

..


*filelist = (struct filelist*)realloc(filelist[filecount -1],24*filecount);

filelist = add_file(filelist[filecount],fname,filecount);

.....
////



The Above code is showing error -- Segmentation Fault
(gdb) n

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400bd2 in add_file (rptr=0x604050, 
    name=0x604075 "CommandFile2.txt", filecount=2) at assign1.c:47
47      rptr[filecount - 1]->filename = (char *)malloc(10 * sizeof(char *));

Can anyone tell me the correct code to allocate memory so that it does not give SegF I gives me error while allocating memory for the same. I can allocate memory for first file storage, but it fails during second file storage. why doe it happen. what makes it to fail. why it is not allocating memory and not storing filename in it.

Aucun commentaire:

Enregistrer un commentaire