c - How do I free up the memory consumed by a string literal? -


how free memory used char* after it's no longer useful?

i have struct

struct information { /* code */ char * filename; } 

i'm going save file name in char*, after using time afterwards, want free memory used take, how do this?

e: didn't mean free pointer, space pointed filename, string literal.

there multiple string "types" filename may point to:

  1. space returned malloc, calloc, or realloc. in case, use free.

  2. a string literal. if assign info.filename = "some string", there no way. string literal written in executable itsself , stored program's code. there reason string literal should accessed const char* , c++ allows const char*s point them.

  3. a string on stack char str[] = "some string";. use curly braces confine scope , lifetime that:

    struct information info; {     char str[] = "some string";     info.filename = str; } printf("%s\n", info.filename); 

    the printf call results in undefined behavior since str has gone out of scope, string has been deallocated.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -