Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

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

  imsi = "405750111";

  strncpy(dest,imsi,5);

  printf("%s",dest);

  /*  i = 10; */
}

In the above code, with the i = 10 assignment is commented as above, the code works fine without error. When assignment is included for compilation, the error (segmentation fault) occurs at strncpy(dest,imsi,5);.

By avoiding optimization to variable i (i.e., volatile int i;), the error is cleared even with the assignment (i = 10) included.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...