Search code examples
cfreedynamic-arrays

I operated on the name of the array and didn't get error or warnings why?


I wrote a code expecting to receive error along with the description expression must be a modifiable value but i didn't, I don't understand can arrays that were dynamically allocated be modified?

{
    int* x;
    x =(int*) malloc(3 * sizeof(int));
    if (x == 0)
    {
        printf("sorry met an error");
        exit(1);
    }
    x[0] = 0;
    x[1] = 1;
    x[2] = 2;
    printf("%p\n", x);
    printf("%d\n", x[0]);
    printf("%d\n", sizeof(x));
    x++;
    printf("%p\n", x);
    printf("%d\n", x[0]);
    printf("%d\n", x[1]);
    printf("%d", sizeof(x));
    free(x);
    return 0;
}

By the way the free function here is also triggering a breakpoint any ideas why?


Solution

  • x is a pointer to the first element in an array. (x is not an array.)

    As x is not const, you are free to modify it. x++ modifies it to point to the second element in the array.

    When you then attempt to free the dynamically-allocated array (free(x)) you are passing free() a value that malloc did not give you. Hence the debugger triggering a break.

    Either restore x to its prior value before attempting to free it, or use a different pointer variable to play arithmetic and leave x alone.