munmap_chunk(): invalid pointer

前端 未结 2 535
无人及你
无人及你 2021-01-31 02:53

I\'ve spotted the error in my program and decided to write a simple one, which would help me understand what\'s going on. Here it is :

#include 
#         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 02:59

    In function char * second

     char * word = malloc(sizeof(char) * 10);
     word = "ab";
    

    The second statement word = "ab"; changes word to point away from the allocated memory.You are not copying the string "ab" to the area of heap allocated by malloc.

    And to free a memory that is not allocated by malloc or similar functions crashes your program.

    Attempting to free an invalid pointer (a pointer to a memory block that was not allocated by calloc, malloc, or realloc) may affect subsequent allocation requests and cause errors.

    You should use here strcpy as also suggested by others.

提交回复
热议问题