0

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.

4
  • 3
    SFR *sfr = malloc(sizeof(SFR *)); => SFR *sfr = malloc( sizeof( SFR ) ); Commented Nov 18, 2022 at 5:30
  • @AviBerger Why do you not consider that an answer? A little explanation might even make it a good one. Commented Nov 18, 2022 at 5:33
  • It's basically just a typo, the later "malloc((sizeof(int)) * urlSize);" suggests to me that the OP understands it - though overlooked it, and I should be getting to bed. Commented Nov 18, 2022 at 5:45
  • the problem is simple: you are asking to allocate a SFR * that can contain a SFR * which is obviously impossible Commented Nov 18, 2022 at 7:33

1 Answer 1

1

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.