'strcpy' with 'malloc'?

后端 未结 6 1636
予麋鹿
予麋鹿 2020-12-09 10:29

Is it safe to do something like the following?

#include 
#include 
#include 

int main(void)
{
    char* msg;
         


        
6条回答
  •  醉梦人生
    2020-12-09 11:25

     char* msg;
     strcpy(msg, "Hello World!!!");  //<---------Ewwwww
     printf("%s\n", msg); 
    

    This is UB. No second thoughts. msg is a wild pointer and trying to dereference it might cause segfault on your implementation.

    msg to be pointing to a valid memory location large enough to hold "Hello World".

    Try

    char* msg = malloc(15);
    strcpy(msg, "Hello World!!!");
    

    or

    char msg[20]; 
    strcpy(msg, "Hello World!!!");
    

提交回复
热议问题