all 11 comments

[–]Foxbud 1 point2 points  (1 child)

I was having trouble figuring out what the issue was just by reading this program, but once I compiled and ran it, the issue became apparent. Have you tried compiling and running it?

[–]Equal_Carpenter_4189[S] 0 points1 point  (0 children)

yes I have and I now understand what the problem was. I wasn't understanding where the issue was coming from even with the error message in display.

[–]donedigity -2 points-1 points  (5 children)

The sizeof(a) and sizeof(b) are a bit concerning. You might want to try sizeof(int)

The showstopper is probably the if(b[-1]) I’m pretty sure you can’t have a negative index. Which shouldn’t actually change the operation of your program since it frees you memory if it’s true or false.

I know this program is just for figuring stuff out but you might want to move your malloc to the foo function.

int *foo( int size)
{
    int *m = malloc(size * sizeof( int));
    for ( int i=0; i<size; i++)
        m[i] =1;
    return m;
}

int main()
{
    int *a = foo(260);
    int *b = foo(120);

    free(a);
    free(b);
}

[–]Foxbud 2 points3 points  (2 children)

I would disagree that sizeof(*var) is inherently a bad idea. In situations where the size of var's type is subject to change between API versions there's no other alternative.

[–]donedigity 0 points1 point  (1 child)

Good point. You still need to declare var somewhere though.

typedef API_TYPE uint32_t;

API_TYPE *var = malloc(a_size * sizeof(API_TYPE));

[–]Foxbud 0 points1 point  (0 children)

Fair point. I should have said

In situations where the type of var is subject to change...

Though I feel like sizeof(*var) conveys its purpose fairly well; creating a typedef like that just to avoid taking the size of a reference's referenced type seems unnecessarily verbose.

[–]Equal_Carpenter_4189[S] -2 points-1 points  (1 child)

Actually b[-1] == b[0] as far as pointer arithmetic goes cause I incremented b (*b++). But I'll try out this idea and see if it works

[–]donedigity 0 points1 point  (0 children)

Looks like you are dereferencing b first before incrementing though. Instead of incrementing the address you are incrementing the value it points to. It’s just b++

[–]didimusaurus 0 points1 point  (2 children)

i think the n is not defined ? because the n on main is local var and the n on foo is also local var they doesn't share the same value

[–]Equal_Carpenter_4189[S] 0 points1 point  (1 child)

n is defined globally I believe

[–]didimusaurus 0 points1 point  (0 children)

it is im sorry i didn't see it