[SOLVED] does snprintf() allocate memory and does it need to be deallocated ?
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Does the above code allocate 10 bytes to variable 'fileToBeOpened' and does the variable 'fileToBeOpened' need to be free() ?
I couldn't find much information on this from Google !
Kindly guide !
no, it does not. Your call would store at most 10 characters (incl. the terminating NUL '\0' character) in the string, but it relies on the caller to allocate the appropriate amount of memory.
The alternative to snprintf would be asprintf/asnprintf which allocates memory for you. In this case, you would then have to call free for the returned memory address. BUT, keep in mind that asprintf/asnprintf is NOT part of the C99 standard (or any C standard), though you can't rely on the portibility of this function ...
variable 'fileToBeOpened' is a char*, so does the data stored in variable 'FILEPATH' gets stored in memory and 'fileToBeOpened' just points to it ?
Is it so ?
If that _would_ be the case, the interface would require to pass in a char** due to the call-by-value parameter passing by C, but in this case you just pass in a char * so that snprintf can't return the new address ...
If there is no allocation, Where do these 10 characters get stored then ? (I mean how do they get stored in the variable 'fileToBeOpened')
Oh I am sorry for this question !!
I did overlook the fact that I unless I myself allocate memory to the variable 'fileToBeOpened' the above shown code will give me a segmentation fault !!!!
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.