简体   繁体   中英

Freeing a pointer in a structure referenced by a pointer

I have a pointer to several structures that have been allocated memory via:

STRUCTNAME *ptr;
ptr = (STRUCTNAME *)malloc(sizeof(STRUCTNAME)*numberOfStructs);

The structures are accessed via a offset like so:

(ptr + i)->field;

The structures have 2 fields that are character pointers as follows:

typedef struct
{
    char *first;
    char *second;
}STUCTNAME;

These fields are allocated memory as follows:

(ptr + i)->first = (char *)malloc(strlen(buffer));

This appears to work but when I try to free the pointers within the structures I get a segmentation fault 11 when I do this:

free((prt + i)->first);

Help?

Notes: buffer is a character array. Offsetting a pointer by a integer should increment the pointer by the size of what it is pointing to times the integer correct?

Here is a link to my full source code. I have not written some of the functions and I am not using the freeAllpointers and printAll yet. https://drive.google.com/file/d/0B6UPDg-HHAHfdjhUSU95aEVBb0U/edit?usp=sharing

OH! Thanks everyone! Have a happy Thanksgiving! =D (If you're into that kinda stuff)

  • In case, you don't initialize all those members in that piece of code, you're not showing us:
    Allocate the struct storage ( STRUCTNAME* ) with calloc() , so that all allocated memory, namely first and second are zero at the beginning. Passing NULL to free() will result in a no-op. Passing any wild (garbage) pointer to free() may cause a segmentation fault.
  • To detect a double-free, set ptr[i].first = NULL; after free(ptr[i].first); as a defensive measure for testing.

Notes: buffer is a character array. Offsetting a pointer by a integer should increment the pointer by the size of what it is pointing to times the integer correct?

Yes, except for void* on those compilers, which don't define sizeof(void) , which is defined to have undefined behavior, to a value > 0: What is the size of void?

Edit:

void makeReviews(FILE *input, REVIEW *rPtr, int numReviews) <-- This does NOT return the new value of rPtr . In main() , it will remain NULL . Do something like this:

REVIEW* makeReviews(FILE *input, int numReviews);
//...
int main(){
    //...
    rPtr = makeReviews(input,numReviews);
    //...
}

or

void makeReviews(FILE** input,REVIEW** rPtrPtr,int numReviews){
    REVIEW* rPtr = *rPtrPtr;
    //...
    *rPtrPtr = rPtr;
}
//...
int main(){
    //...
    makeReviews(input,&rPtr,numReviews);
    //...
}

fgets(cNumReviews, sizeof(cNumReviews), input); <-- Perhaps, you could use something like fscanf() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM