The general trick has to do with how the program's code and variables are layed out in memory. For example, when a function is called the program (code inserted by the compiler) must store the address of the instruction to return to. So if this is the 32 bit word just before the beginning of the stack, one could do:

 void foo()
 {
    int array[5];
    int var = 0;
    int var2 = 0;

    // read in user input
    printf("Enter index and value to write:");
    scanf("%i", var);
    scanf("%i", var2);

    // malicious user might set var to -1 and var2 to an address to execute
    // if say the 32-bit value before the stack variables is the instruction to
    // return to
    array[var] = var2

    // return now goes to malicious code
 }

(So your job is to construct code so that such a thing is not possible. :) )

The rules for how a function call is implemented, stack variables allocated, values passed, and return values returned back is called the calling convention. I reccomend reading the attached article for a good indepth coverage of C calling conventionts.

Answer from Doug T. on Stack Overflow
Top answer
1 of 3
11

The general trick has to do with how the program's code and variables are layed out in memory. For example, when a function is called the program (code inserted by the compiler) must store the address of the instruction to return to. So if this is the 32 bit word just before the beginning of the stack, one could do:

 void foo()
 {
    int array[5];
    int var = 0;
    int var2 = 0;

    // read in user input
    printf("Enter index and value to write:");
    scanf("%i", var);
    scanf("%i", var2);

    // malicious user might set var to -1 and var2 to an address to execute
    // if say the 32-bit value before the stack variables is the instruction to
    // return to
    array[var] = var2

    // return now goes to malicious code
 }

(So your job is to construct code so that such a thing is not possible. :) )

The rules for how a function call is implemented, stack variables allocated, values passed, and return values returned back is called the calling convention. I reccomend reading the attached article for a good indepth coverage of C calling conventionts.

2 of 3
2

If you allocate a buffer on the stack, and it overflows, it writes onto the stack. The stack contains the return pointer for the function that allocated the buffer. So, if you overflow a buffer on the stack, you can set the return pointer to something arbitrary; thereby giving you control of the thread of execution.

As to actually injecting the code, that depends. The stack - or rather, the page containing it - is often set not to allow code execution; but historically it would have been possible to store small malicious programs in the buffer itself on the stack. Return oriented programming is a fairly new variant of the return-to-libc attack, both of which work around NX bits.

🌐
OWASP Foundation
owasp.org › www-community › attacks › Code_Injection
Code Injection | OWASP Foundation
Author: Weilin Zhong, Rezos ... Bergman, Camilo, Andrew Smith, kingthorin · Code Injection is the general term for attack types which consist of injecting code that is then interpreted/executed by the application. This type of attack exploits poor handling of untrusted data. These types of attacks are usually made possible due to a lack of proper input/output data validation, for example...
Discussions

exploit - C/C++ code injection - Information Security Stack Exchange
I think you are confused between overflows,code injection and shell execute function. ... An injection attack is when you can get a program to interpret data in a way unintended by the developer. For example, ' OR 1=1 --, the single apostrophe is interpreted as "end of string", not just as data. More on security.stackexchange.com
🌐 security.stackexchange.com
October 29, 2019
ELI5: How does code injection work? How can something be ran by user input, can't you just avoid letting user input run code?
It can only happen from user input, and you should never need to run it, but in the some cases, like SQL injection, one error in the dev's code can make an entire site vulnerable. Have a look at this Computerphile video. More on reddit.com
🌐 r/explainlikeimfive
13
0
February 3, 2015
How do I inject code with a buffer overflow attack?
Check out liveoverflow. He has a video that will do exactly this IIRC. If you’re reading input with gets then you can just overwrite the buffer and subsequently the return address with the desired function’s address. More on reddit.com
🌐 r/C_Programming
21
33
May 3, 2019
ELI5: How do hackers "inject" code into a webpage, like in the Newegg checkout process?
There are two main types of code injection vulnerabilities for websites: SQL injection and cross-site scripting (XSS). SQL is the language used to retrieve information from the database. In general queries are formatted like this: SELECT [attributes] FROM [table name] WHERE [condition] For example if you search for "hammer" in a DIY catalog, it may look like this: SELECT brand, name, price FROM tools WHERE type= "hammer" In this case, "hammer" is chosen by the user, and should be handled carefully. An attacker could write some SQL there, and create the following query: SELECT brand, name, price FROM tools WHERE type = "hammer AND SELECT password FROM passwords" Computerphile has a nice video explaining it and also an actual example . In a similar way, attackers can also inject scripts into HTML pages. If you rightclick on any webpage and select "view page source", you can find some More on reddit.com
🌐 r/explainlikeimfive
6
13
September 20, 2018

The general trick has to do with how the program's code and variables are layed out in memory. For example, when a function is called the program (code inserted by the compiler) must store the address of the instruction to return to. So if this is the 32 bit word just before the beginning of the stack, one could do:

 void foo()
 {
    int array[5];
    int var = 0;
    int var2 = 0;

    // read in user input
    printf("Enter index and value to write:");
    scanf("%i", var);
    scanf("%i", var2);

    // malicious user might set var to -1 and var2 to an address to execute
    // if say the 32-bit value before the stack variables is the instruction to
    // return to
    array[var] = var2

    // return now goes to malicious code
 }

(So your job is to construct code so that such a thing is not possible. :) )

The rules for how a function call is implemented, stack variables allocated, values passed, and return values returned back is called the calling convention. I reccomend reading the attached article for a good indepth coverage of C calling conventionts.

Answer from Doug T. on Stack Overflow
🌐
Wikipedia
en.wikipedia.org › wiki › Code_injection
Code injection - Wikipedia
February 14, 2026 - Code injection could, for example: Introduce a useful new column that did not appear in the original design of a search results page. Offer a new way to filter, order, or group data by using a field not exposed in the default functions of the original design.
🌐
InformIT
informit.com › articles › article.aspx
Code Injection | Secure Coding in C and C++: Strings | InformIT
The get password program shown in Figure 2–9 can also be exploited to execute arbitrary code. This time, the program was compiled for Red Hat Linux 9.0 using GCC. An exploit can be injected into the program via a binary data file (as shown in Figure 2–24) from a file using redirection as follows:
🌐
Kuleuven
cs.kuleuven.be › publicaties › rapporten › cw › CW386.pdf pdf
Code Injection in C and C++ : A Survey of Vulnerabilities and Countermeasures
So in the example in figure 6 the return address would be · overwritten with a pointer to code that will jump over the place where fd will · be stored and will execute code that the attacker injected. As with the indirect · pointer overwrite this technique can be used to overwrite arbitrary memory ·
🌐
GeeksforGeeks
geeksforgeeks.org › code-injection-mitigation-example
Code Injection and Mitigation with Example - GeeksforGeeks
September 29, 2022 - Many solutions have been developed for thwarting these types of code injection attacks, for both application and architecture domain. Some examples include input validation, parameterization, privilege setting for different actions, addition of extra layer of protection and others. Example: When a developer uses the PHP eval() function and passes it untrusted data that an attacker can modify, code injection could be possible.
Find elsewhere
🌐
Stack Exchange
security.stackexchange.com › questions › 220359 › c-c-code-injection
exploit - C/C++ code injection - Information Security Stack Exchange
October 29, 2019 - You can use the same technique in C or C++ programs, as long as the same requirements are given. For example, if a C++ program builds an SQL query based on user input, it may be vulnerable to SQL Injection.
🌐
DZone
dzone.com › software design and architecture › security › code injection – examples and prevention
Code Injection – Examples and Prevention
November 21, 2021 - A successful exploit grants attackers access to the application’s server-side interpreter, following which the attackers can use system calls to run commands on the server and penetrate further for deeper exploitation. Types of code injection attacks differ depending on the programming language used to develop the application’s source code and the attacker’s malicious code.
🌐
Bright Security
brightsec.com › blog › code-injection-example
Code Injection Example: A Guide to Discovering and Preventing attacks - Bright Security
March 25, 2025 - The most popular example perhaps is Dropbox. They utilize code injection to make some online functionalities available in the offline use of their tools. Conversely, however, bad coding practices can very easily lead to code injection, as a user might unknowingly use the reserved program keyword due to the developer not sanitizing it correctly or in time.
🌐
ired.team
ired.team › offensive-security › code-injection-process-injection
Code & Process Injection | Red Team Notes
October 26, 2018 - CreateRemoteThread Shellcode InjectionDLL InjectionReflective DLL InjectionShellcode Reflective DLL InjectionProcess DoppelgangingLoading and Executing Shellcode From PE ResourcesProcess Hollowing and Portable Executable RelocationsAPC Queue Code InjectionEarly Bird APC Queue Code InjectionShellcode Execution in a Local Process with QueueUserAPC and NtTestAlertShellcode Execution through FibersShellcode Execution via CreateThreadpoolWaitLocal Shellcode Execution without Windows APIsInjecting to Remote Process via Thread HijackingSetWindowHookEx Code InjectionFinding Kernel32 Base and Function
🌐
Indusface
indusface.com › learning › code-injection
What is Code Injection & how can it be prevented? | Indusface
May 30, 2025 - The double dash (– ) turns the rest of the query into a comment, causing the password check to be ignored. This lets the attacker log in as an administrator without knowing the actual password. Attackers often experiment with different code injection techniques to extract sensitive information or gain unauthorized access.
🌐
ScienceDirect
sciencedirect.com › topics › computer-science › code-injection-attack
Code Injection Attack - an overview | ScienceDirect Topics
Code injection (CI) attacks exploit the lack of memory checks to mount an attack. First, a CI attack corrupts the stack of a process by overwriting parts of it with malicious data. For example, Listing 3 shows a process that asks the user for an input and stores it on the stack.
🌐
GitHub
cocomelonc.github.io › tutorial › 2021 › 09 › 18 › malware-injection-1.html
Classic code injection into the process. Simple C++ malware. - cocomelonc
September 18, 2021 - In this post we will discuss about a classic technique which are payload injection using debugging API. Firstly, let’s go to prepare our payload. For simplicity, we use msfvenom reverse shell payload from Kali linux. ... where 10.9.1.6 is our attacker’s machine IP address, and 4444 is port which we run listener later. Let’s start with simple C++ code of our malware, which is used by me in AV evasion part 1 post: /* cpp implementation malware example with msfvenom payload */ #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // our payload: reverse shell (msfv
🌐
GitHub
cocomelonc.github.io › tutorial › 2021 › 12 › 13 › malware-injection-12.html
Code injection via memory sections. Simple C++ example. - cocomelonc
December 13, 2021 - Changes to the local view of the section will also cause remote views to be modified as well, thus bypassing the need for APIs such as KERNEL32.DLL!WriteProcessMemory to write malicious code into remote process address space.
🌐
Wisc
research.cs.wisc.edu › mist › SoftwareSecurityCourse › Chapters › 3_8_3-Code-Injections.pdf pdf
We are in the process of renumbering ...
Contacts: bart@cs.wisc.edu and elisa@cs.wisc.edu · © 2023-2026 Barton P. Miller and Elisa Heymann All rights reserved. Instructors may link to this page and students are free to use these resources for their personal use
🌐
Cycode
cycode.com › home › code injection attacks
Code injection attacks: Examples and mitigation | Cycode
August 31, 2025 - There are many attack vectors for code injection and they are always developing. Injection attacks can occur through entry points like web forms, API endpoints, URL parameters, and even file uploads. Take, for example, input fields such as search boxes or comment sections that seem harmless, which can be used to place an injected query if not protected/sanitized properly.
🌐
Andrea Fortuna
andreafortuna.org › 2019 › 03 › 06 › a-simple-windows-code-injection-example-written-in-c
A simple Windows code Injection example written in C# | Andrea Fortuna
March 6, 2019 - Lines 84 - 88: some code to covert the shellcode string into byte array · Line 91: calls VirtualAllocEx, in order to allocate a memory area in target process.
🌐
Snyk Learn
learn.snyk.io › home › security education › what is code injection? | tutorial & examples
What is code injection? | Tutorial & examples | Snyk Learn
October 28, 2025 - For example, instead of the vulnerable example from our lesson, which looks like this: We could remove the shell (sh -c) and pass the arguments directly and safely to the echo command.
🌐
GitHub
github.com › topics › code-injection
code-injection · GitHub Topics · GitHub
Advanced Game Hacking Library for C, Modern C++, Rust and Python (Windows/Linux/FreeBSD) (Process/Memory Hacking) (Hooking/Detouring) (Cross Platform) (x86/x64) (DLL/SO Injection) (Internal/External) (Assembler/Disassembler) python c rust hook c-plus-plus memory assembler disassembler process game-hacking code-injection syscall function-call detour-hook library-injection
🌐
Kaspersky IT Encyclopedia
encyclopedia.kaspersky.com › glossary › code-injection
Code injection | Kaspersky IT Encyclopedia
December 11, 2018 - – The articles in the Vulnerabilities and Hackers section is devoted to the topic of software vulnerabilities and how cybercriminals exploit them, as well as legislation and hackers in the broad sense of the word. ... Code injection refers to the activity of manipulating a vulnerable program in order to execute arbitrary code – the malicious code is injected into the running process of the vulnerable program. This is possible when a program allows unsafe user-supplied data (for example, due to lack of boundary checks) to become part of the code of being executed, this often leading to the execution of a system shell: note that the malicious code is executed with the same privileges as the vulnerable program.