Does printf() allocate memory in C?

前端 未结 3 421
迷失自我
迷失自我 2021-01-15 05:39

This simple method just creates an array of dynamic size n and initializes it with values 0 ... n-1. It contains a mistake, malloc() allocates just n instead of sizeof(int)

3条回答
  •  醉梦人生
    2021-01-15 06:22

    You allocate 8 bytes for the array, but you store 8 int, each of which is at least 2 bytes (probably 4), so you are writing past the end of the allocated memory. Doing so invokes undefined behavior.

    When you invoke undefined behavior, anything can happen. Your program can crash, it can show unexpected results, or it can appear to work properly. A seemingly unrelated change can change which of the above actions occur.

    Fix the memory allocation, and you code will work as expected.

    int *result = malloc(sizeof(int) * n);
    

提交回复
热议问题