简体   繁体   中英

Heap Buffer Overflow when assigning array in C

I want to malloc an array, but I get a heap overflow error when trying to do so. I have tried to find a solution but I could not figure it out. Here is my code:

typedef struct scaledFootrule {
    double minTotalSFR;
    int *tempPermutation;
} SFR;

static SFR *sfrStruct(int urlSize) {
    SFR *sfr = malloc(sizeof(SFR *));
    if (sfr == NULL) {
        fprintf(stderr, "error: out of memory\n");
        exit(EXIT_FAILURE);
    }
    sfr->minTotalSFR     = MAX_TOTAL_SFR_DIST;
    sfr->tempPermutation = malloc((sizeof(int)) * urlSize);    
    return sfr;
}

When running, it gives this error:

==1646450==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000198 at pc 0x0000004c8d21 bp 0x7ffe39cd42b0 sp 0x7ffe39cd42a8 WRITE of size 8 at 0x602000000198 thread T0

Thanks, and sorry if the solution is trivial.

Correctness

SFR *sfr = malloc(sizeof(SFR *)); is an insufficient allocation.

Avoid allocation type mistakes. Allocate to the referenced object, not the type.

//                   v-----------v    This is the size of a pointer 
// SFR *sfr = malloc(sizeof(SFR *));
SFR *sfr = malloc(sizeof sfr[0]);
//                ^-----------^ This is the size of one object.     

Review

Consider the next case. It it right? To review, we need to find the sfr definition and then the SFR definition, wherever they may be, perhaps another file. By using the referenced object size, code becomes easier to review.

// sfr->tempPermutation = malloc((sizeof(int)) * urlSize); 
sfr->tempPermutation = malloc(sizeof sfr->tempPermutation[0] * urlSize); 

Maintenance

Suppose .tempPermutation no longer points to an int , but a long long . By coding to the size of the referenced object and not type, no changes needed in the allocations. Easier to maintain than coding in the type.

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