What is the trick behind strcpy()/uninitialized char pointer this code?

后端 未结 3 1305
长发绾君心
长发绾君心 2021-01-23 01:48
#include 
#include 
#include 

void main ()
{
  char *imsi;
  unsigned int i;
  int val;
  char *dest;

  imsi = \"4057501         


        
3条回答
  •  天命终不由人
    2021-01-23 02:09

    In your code, by saying

     strncpy(dest,imsi,5);
    

    you're trying to write into an unitialized pointer dest. It can (and most possibly, it will) point to some memory which is not accessible from your program (invalid memory). It invokes undefined behavior.

    There is nothing that can be guaranteed about a program having UB. It can work as expected (depends on what you're expecting, actually) or it may crash or open your bank account and transfer all money to some potential terrorist organization.

    N.B - I hope by reading last line you got scared, so the bottom line is

    Don't try to write into any uninitialized pointer (memory area). Period.

提交回复
热议问题