So I have two simple programs. They are very similar, but one code works just fine and other one doesn't work at all. Does anyone here idea why?
This code works without problems, despite char* name not being initialized.
#include <dirent.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
DIR* d;
struct dirent* dir;
char* name;
d=opendir(".");
if(d){
while((dir=readdir(d))!=NULL){
strcpy(name,dir->d_name);
printf("%s\n",name);
}
clode(dir);
}
return 0;
}
The second code has minor difference in the declaration section and this results in the variable 'name' being unreachable.
int main(int argc, char* argv[]){
DIR* d;
struct dirent* dir;
char* surname = "Surname";
char* name;
d=opendir(".");
if(d){
while((dir=readdir(d))!=NULL){
strcpy(name,dir->d_name);
printf("%s\n",name);
}
clode(dir);
}
return 0;
}
When running the second code, I get a "Segmentation fault" immediately after strcpy(name,dir->d_name)
and when I try to print variable 'name' under the GDB debugger I get the message $1 = 0x1 <error: Cannot access memory under address 0x1>
.
Why didn't this error message appear in first program? And what is big deal with declaring char* surname = "Surname";
that makes this kind of runtime error?
P.S. I know that in this example I never use variable 'surname' and I am aware that strcpy(name,dir->d_name)
isn't needed in this code. This code is part of much bigger code and this is result of extracting important parts which cause the error (in an attempt to produce a more minimal set of code).
Thank you. Regards