Re: How far should one go preventing potential memory leaks?
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: How far should one go preventing potential memory leaks?
- From: Thomas Jericke <tjericke@...>
- Date: 2016年5月10日 10:22:07 +0200
On 05/10/2016 09:42 AM, Marc Balmer wrote:
Am 10.05.2016 um 09:13 schrieb Thomas Jericke <tjericke@indel.ch>:
On 05/10/2016 09:10 AM, Thomas Jericke wrote:
On 05/10/2016 08:41 AM, Marc Balmer wrote:
This prevents a memory leak if lua_pushstring() raises an error, but I will end
up with a number of rather small allocations that are only used for a short
period of time.
If they buffers are really that small, I would just use the stack.
char s[32];
snprintf(s, sizeof(s), "bumblebee");
lua_pushstring(L, s);
PS. I swear I typed this before I saw Sean's answer :-/
Hehe ;)
Well, in the real code the allocations are made for user supplied parameters, so I don't
know neither the size of the parameters not their count (which can be up to 65535), so
I really need to allocate the memory.
However, many thanks to everyone who replied.
You can reuse the buffer and you can make a fall-back for large parameters.
char buff[1024];
for(unsigned long index = 0; index < 65535; index++) {
size_t len = strlen(args[index]);
if(len + 6 <= sizeof(buff)) {
sprintf(buff, "arg1=%s", args[index]);
lua_pushstring(L, buff);
}
else {
char *s = lua_newuserdata(L, len + 6);
sprintf(s, "bumblebee");
lua_pushstring(L, s)
}
}
Assuming you need the strlen anyway to know how large your buffer must
be, it is only an additional "if".
I think most of the time the additional "if" statement will pay off. If
you want to be sure you can simply profile your parameter length.
--
Thomas