'strcpy' with 'malloc'?

后端 未结 6 1637
予麋鹿
予麋鹿 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:10

    The first version is not safe. And, msg should be pointing to valid memory location for "Hello World!!!" to get copied.

    char* msg = (char*)malloc(sizeof(char) * 15);
    strcpy(msg, "Hello World!!!");
    
    0 讨论(0)
  • 2020-12-09 11:15

    You need to allocate the space. Use malloc before the strcpy.

    0 讨论(0)
  • 2020-12-09 11:16

    strdup does the malloc and strcpy for you

    char *msg = strdup("hello world");
    
    0 讨论(0)
  • 2020-12-09 11:21

    Your original code does not assign msg. Attempting to strcpy to it would be bad. You need to allocate some space before you strcpy into it. You could use malloc as you suggest or allocate space on the stack like this:

    char msg[15];
    

    If you malloc the memory you should remember to free it at some point. If you allocate on the stack the memory will be automatically returned to the stack when it goes out of scope (e.g. the function exits). In both cases you need to be careful to allocate enough to be able to copy the longest string into it. You might want to take a look at strncpy to avoid overflowing the array.

    0 讨论(0)
  • 2020-12-09 11:24

    Use:

    #define MYSTRDUP(str,lit) strcpy(str = malloc(strlen(lit)+1), lit)
    

    And now it's easy and standard conforming:

    char *s;
    MYSTRDUP(s, "foo bar");
    
    0 讨论(0)
  • 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!!!");
    
    0 讨论(0)
提交回复
热议问题