malloc vs array in C

后端 未结 4 1803
时光说笑
时光说笑 2021-01-02 07:42

I am taking an open online course CS50 from Harvard. The last lecture I had was about memory allocation and pointers (two concepts which are absolutely new to me).

4条回答
  •  余生分开走
    2021-01-02 08:07

    1. Is in the code snippet above c also a pointer of type char*?

    No it is not. It is an array of ten char.

    However, the name of an array can, when used in a context where a pointer is expected, be converted to a pointer, and therefore effectively used as if it is a pointer.

    1. Does char c[10] also reserve memory on the heap as malloc does?

    No. Heap and stack are not completely accurate terms either, but I won't expand on that further.

    What malloc() does is called "dynamic memory allocation" according to the standard.

    The behaviour of char c[10]; depends on context.

    • If it is inside a block scope (inside a pair of {}) it creates an array of automatic storage duration. That array ceases to exist, as far as your program is concerned, when the scope is exited (e.g. if the function returns).
    • If it is at file scope (outside a function), then it creates an array of static storage duration. The array will be created once, and continue to exist until program termination.
    1. Are the ways to allocate memory equivalent?

    Nope.

    char c[3] = "aaa";free(c); returns a runtime error; so it seems I can not free the memory I have allocated with char c[3]. Why is that?

    Because free() only has defined behaviour when passed a pointer to dynamically allocated memory - i.e. returned by malloc(), calloc(), or realloc() or a NULL pointer (which causes free() to do nothing).

    c is an array of either static or automatic storage duration, depending on context, as I mentioned above. It is not dynamically allocated, so passing it to free() gives undefined behaviour. A common symptom of that is a runtime error, but not the only possible symptom.

提交回复
热议问题