Oops...

Story: Validating Untrusted Integer InputsTotal Replies: 5
Author Content
softwarejanitor

Jan 16, 2009
2:06 PM EDT
I think the example has an error in it. I think the declaration of str should have an initialization added to it, otherwise if the compiler does not automatically initialize pointers to null, it is possible that the free will cause a seg fault.
dinotrac

Jan 16, 2009
5:02 PM EDT
sj -

It's fine. Notice that the free happens only if size > 0. In that case, the malloc is always performed and it will set the pointer to null if the allocation fails. freeing a null pointer is, essentially, a no op.

Not a problem.

I could, of course, be wrong -- not the world's greatest programmer, but I've stepped on enough pointers to feel pretty good about this one.



softwarejanitor

Jan 16, 2009
6:45 PM EDT
dino -- No, the malloc does not always happen, it only happens if str is null, and since str is not explicitly initialized, that is not a safe assumption. If str is some random value left in memory then the malloc will not happen and the free will try to free that random address which will be highly unlikely to be within the allocated address space for that process and will therefore generate a seg fault. The value of size matters (heh), but since the value of str also matters as to whether or not the malloc and free get called it isn't the only thing to look at.

I've spent years and years fixing this sort of glitch... usually in code written by greenhorns, but occasionally even by someone who should have known better.
dinotrac

Jan 16, 2009
6:57 PM EDT
Sorry - Got the code snippets confused.

And yes --- You're right. If str is not initialized to null -- either by the compiler or the coder, the code is a segfault waiting to happen.
theboomboomcars

Jan 16, 2009
11:43 PM EDT
dino I think you need more sleep or something you have misremembered the facts frequently lately. I don't want to say your wrong since your never wrong, but something is up.
dinotrac

Jan 17, 2009
8:02 AM EDT
boomboom -

I appreciate your concern. I've been a bit worried myself lately. No wait - I haven't, or... maybe i have.

Could I be wrong about that? At least I could be right about being wrong. Or am I wrong that I was right about being wrong.

Sigh.



Posting in this forum is limited to members of the group: [ForumMods, SITEADMINS, MEMBERS.]

Becoming a member of LXer is easy and free. Join Us!