面試 改錯題-1

Problem

Find as many issues as possible and correct them:
malloc(n) allocates n bytes in the heap.

int main(void)
{
    int *ptr = (int *) malloc(10);
    for(int i =0; i <10; i++)
    {
        *ptr++ = i;
    }
    free(ptr);
}


Solution

  1. line 3 -- 10 integers should have the size of 10 * sizeof(int);
  2. line 8 -- ptr is not original pointer allocated -- free(ptr - 10)
  3. ptr is used without checking its validity
  4. missing header files <stdlib.h> or <malloc.h>
  5. misssing return statement, but it is ok for main() because it is only one function that can implicitly return 0  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章