c - segmentation fault while calling strlen with a previously allocated pointer -


up until have had code worked regarding variable called wfiles. wfiles initialized within main file:

char* wfiles = ""; 

which far can tell c has no complaints. next wfiles variable allocated in switch statement:

 switch (c) {     case 't':         /* user wants template */         template = optarg;         break;     case 'f':         wfiles = optarg;         break;     case 'v':         vcs = optarg;         break;     case 'u':         url = optarg;         break;     case 's':         /* custom save location */         save_loc = optarg;         break;     case '?':         break;     default:         abort();     } 

finally check whether or not wfiles empty:

if (!empty(wfiles)) 

empty macro expands (strlen(wfiles) == 0)

i cannot see problems when run code segmentation fault. had never happened before. when ran code in gdb , without debugging symbols, 1 line pointed if statement earlier mentioned. know why is?

strlen() dereference pointer, may cause problems when pointer,i.e optarg, not valid.

for example, in case of optarg=null , c='f', code executed as:

case 'f':     wfiles = optarg;     //now wfiles=null 

strlen(wfiles) be: strlen(null) , segmentation fault happens.

see this related question more reference


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -