c++ - Inputting into a char* declared earlier crashes the program while doing that into a 'just-declared' char* doesn't. Why? -


this code crashes program

#include <cstdio> int main() {     char *name1;     char *name2 = "mark";     gets(name1);     puts(name1);     return 0; } 

whereas doesn't

#include <cstdio> int main() {     char *name1 = "mark";     char *name2;     gets(name2);     puts(name2);     return 0; } 

why ? using mingw code::blocks ide.

you lucky 1 crashes , other doesn't.
both of programs produce undefined behavior.

char *name2; gets(name2); 

you need point pointer valid , big enough memory able write it. writing uninitialized pointer. results in undefined behavior. undefined behavior not mandate crash, literally means behavior possible, in case might crash , may not nevertheless incorrect program.

ideal solution use std::string.
if insist on using char * need point pointer valid memory. e.g.

char myarr[256]; char *name2 = &myarr; 

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -