27

How to write a program in C++ such that it will delete itself after execution ?

20
  • 6
    @Neil: it's a trap!
    – BoltClock
    Aug 11, 2010 at 9:31
  • 2
    Doing so would seem to be unethical. Can't think of a good reason why I'd let something like that run on my computer. Aug 11, 2010 at 9:33
  • 7
    if he has to ask this question it isn't likely he can write a good virus. why are you all so paranoid? maybe it's an installer stub?
    – SpliFF
    Aug 11, 2010 at 9:36
  • 17
    Usually, programs that requires this are programs that should be deleted before execution :)
    – ereOn
    Aug 11, 2010 at 9:37
  • 32
    Surely an uninstaller is a legitimate reason.
    – janm
    Aug 11, 2010 at 9:40

8 Answers 8

30

Here is the code in C which will delete the executable after execution.

#include <Windows.h>
#include <strsafe.h>

#define SELF_REMOVE_STRING  TEXT("cmd.exe /C ping 1.1.1.1 -n 1 -w 3000 > Nul & Del /f /q \"%s\"")

void DelMe()
{
    TCHAR szModuleName[MAX_PATH];
    TCHAR szCmd[2 * MAX_PATH];
    STARTUPINFO si = {0};
    PROCESS_INFORMATION pi = {0};

    GetModuleFileName(NULL, szModuleName, MAX_PATH);

    StringCbPrintf(szCmd, 2 * MAX_PATH, SELF_REMOVE_STRING, szModuleName);

    CreateProcess(NULL, szCmd, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi);

    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
}

void main()
{
    /* Do what you need */

    /* Call this function at the very end of your program to delete itself */
    DelMe();
}
2
  • Not needed to spawn another process and do the useless cmd commands. Just use FILE_FLAG_DELETE_ON_CLOSE. May 29, 2023 at 22:34
  • It works. Amazing Nov 4, 2023 at 22:33
6

On Unix, just call unlink(2) on the executable.

On Windows, you need a second process to help you. The response from st0le seems to be for unlinking a DLL, but for an executable, you would need to start a second process or use an existing process, and then terminate your executable and have the second process do the deletion.

A very simple approach would be to use cmd.exe to help.

An speculative approach that uses any other process could be to allocate some memory in another process and put the filename you want to delete there, then use CreateRemoteThread() to create a suspended thread in the remote process with an entry point of DeleteFile with an argument of a pointer to the memory you allocated. Then exit your process, the thread suspend count should decrement and then DeleteFile should be called to delete your file.

Issues: Memory leak in the remote process, messy.

An easier way might just be to have a supporting DLL using the techniques from st0le's answer.

5

Some Methods

You could also, use some kind of Scheduled Task...

2
3

std::remove(argv[0]) before return in main can do it.

2
  • 1
    You can't actually be 100% sure that argv[0] contains a proper path to the executable. It is supposed to, but there is no enforcement and there are cases in which this is broken for one reason or another. Aug 11, 2010 at 14:44
  • 1
    This answer is not complete, nor accurate. Nevertheless, being this the most simple (and naïve) approach the complete answer should briefly address it, in which cases would work or not, and maybe why.
    – myradio
    Mar 16, 2018 at 13:35
1

For Windows try this. It is basically launching a .bat file that loops until the destruction is sucessful:

http://www.codeproject.com/Articles/4027/Writing-a-self-destructing-exe-file

0

However there is a way to delete the file by itself after execution because every Uninstaller unistalls the software which was installed by it & also deletes the last remaining file i.e., itself such that no files will be remaining in our Hard Disk except some Registry Entries irrespective of the platform it has been installed.

0

I originally posted this solution here.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
    char* process_name = argv[0];
    char command[256] = "start /min cmd /c del ";
    strcat(command, process_name);

    printf("Attempting to delete self...\n");

    system(command);
    return 0;
}

Normally, trying to use system to call the command prompt to delete an executable would not work because the command prompt that is spawned is a child process that system executes and waits for a return status.

This method calls the system to start a command prompt process on its own thread.

The /min argument starts the process as "hidden".
The /c argument supplies arguments to the spawned command prompt.

I know this is an old thread, but I hopes those that come here in the future.

-4

It's a legitimate enough question but it seems you don't understand how executables work. Execution places the program in memory so deleting the disk file is trivial (provided you don't also delete run-time dependencies).

6
  • If it is executed in memory, why can't I (in windows) delete the executable if the program is running? Aug 11, 2010 at 9:35
  • 7
    Execution places parts of the program in memory - many pages may be left on disk to be loaded later , which is why most OSs don't allow you to delete the file representing an executing process.
    – anon
    Aug 11, 2010 at 9:37
  • Ah, I see. That was mainly what I thought would happen. Aug 11, 2010 at 9:39
  • 2
    -1 "so deleting the disk file is trivial" This is incorrect. Program can easily delete itself on linux (if it has enough privileges), but on windows file of a currently running program cannot be deleted until program is terminated.
    – SigTerm
    Aug 11, 2010 at 10:19
  • 1
    Windows (at least, and probably others too) doesn't copy the contents of the executable file into memory, it maps the file into memory, and pages are loaded on demand as they're needed.
    – Will Dean
    Aug 11, 2010 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.