munmap_chunk(): invalid pointer

前端 未结 2 563
无人及你
无人及你 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:55

    In the function second(), the assignment word = "ab"; assigns a new pointer to word, overwriting the pointer obtained through malloc(). When you call free() on the pointer later on, the program crashes because you pass a pointer to free() that has not been obtained through malloc().

    Assigning string literals does not have the effect of copying their content as you might have thought. To copy the content of a string literal, use strcpy():

    strcpy(word, "ab");
    

提交回复
热议问题