Skip to content

Fix Returning of Stack Allocated Memory#29

Merged
pilsnerfrajz merged 1 commit into
mainfrom
stack-allocated-pointers
Sep 24, 2025
Merged

Fix Returning of Stack Allocated Memory#29
pilsnerfrajz merged 1 commit into
mainfrom
stack-allocated-pointers

Conversation

@pilsnerfrajz
Copy link
Copy Markdown
Owner

Returning Stack-Allocated Pointers

This fixes an issue in ping where stack-allocated memory are returned to the caller.

Closes two critical code scanning alerts.

CodeQL

CodeQL detected an error in src/ping.c. The rule says: This rule finds return statements that return pointers to an object allocated on the stack. The lifetime of a stack allocated memory location only lasts until the function returns, and the contents of that memory become undefined after that. Clearly, using a pointer to stack memory after the function has already returned will have undefined results.

The reply header structs for ICMP and ICMP6 were both returned without allocating memory on the heap, which as mentioned in the rule has undefined behavior. The memory could be overwritten, leading to the data inside the struct being overwritten.

File Changes

  • src/ping.c
    • Allocate memory on the heap for the struct icmp *reply_hdr in get_icmp4_reply_hdr()
    • Allocate memory on the heap for the struct icmp *reply_hdr in get_icmp6_reply_hdr()
    • Free the structs if the replies are not echo replies to avoid memory leaks
    • Add note about caller responsibility of freeing structs
    • Free the structs in the calling function

@pilsnerfrajz pilsnerfrajz merged commit 9b15038 into main Sep 24, 2025
5 checks passed
@pilsnerfrajz pilsnerfrajz deleted the stack-allocated-pointers branch September 24, 2025 20:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant