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:
space returned
malloc
,calloc
, orrealloc
. in case, usefree
.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 accessedconst char*
, c++ allowsconst char*
s point them.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 sincestr
has gone out of scope, string has been deallocated.
Comments
Post a Comment