26

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

Paul R
  • 208,748
  • 37
  • 389
  • 560
Saulius
  • 279
  • 1
  • 3
  • 4
  • Now why would you want to do that, I wonder? –  Aug 11 '10 at 09:31
  • 6
    @Neil: it's a trap! – BoltClock Aug 11 '10 at 09:31
  • @Neil: to get a job @007's. I want a job there too, so I'm upvoting any good answer. – devoured elysium Aug 11 '10 at 09:32
  • 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. – Binary Worrier Aug 11 '10 at 09:33
  • I would really love to know about it !! Man that would be so handy :) !! – DumbCoder Aug 11 '10 at 09:33
  • Just delete the executable path? – cpx Aug 11 '10 at 09:36
  • 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 '10 at 09:36
  • 17
    Usually, programs that requires this are programs that should be deleted **before** execution :) – ereOn Aug 11 '10 at 09:37
  • @SpliFF: I don't get what the trouble is also. – devoured elysium Aug 11 '10 at 09:37
  • 29
    Surely an uninstaller is a legitimate reason. – janm Aug 11 '10 at 09:40
  • @Binary Worrier you are right. But this question is interesting from technical point. – Andrey Aug 11 '10 at 09:41
  • 1
    @Janm Have you ever used an installer that deleted itself? I haven't. –  Aug 11 '10 at 09:42
  • 1
    @Neil: Here's a discussion of how to write an uninstaller that deletes itself (on Windows): http://www.drdobbs.com/184416714 – Martin B Aug 11 '10 at 09:45
  • @Martin That was not what I asked. –  Aug 11 '10 at 09:45
  • 1
    @Neil: Point taken -- but then surely advancing the state of the art is a noble cause? (To give the OP the benefit of the doubt...) – Martin B Aug 11 '10 at 09:47
  • @neil: Ultimately they do, there are just multiple steps. On Unix like operating systems, just call unlink(2). Is how to do this on Windows really such secret knowledge? – janm Aug 11 '10 at 09:48
  • 1
    This is actually very simple under most *nixes because of the way files are handled there: `int main(int argc,char **argv) { unlink(argv[0]); puts("and like that...*boof*"); }` – Nordic Mainframe Aug 11 '10 at 09:51
  • @Neil: Perhaps you missed it, but I wrote uninstaller, not installer. – janm Aug 11 '10 at 10:04
  • 1
    There are a number of problems with this question: for starters it's vague (e.g. no OS specified), and it's also been asked and answered in various forms many times on SO already, e.g. http://stackoverflow.com/questions/1606140/can-a-program-delete-its-own-executable – Paul R Aug 11 '10 at 10:23
  • Already answered here: https://stackoverflow.com/questions/1606140/how-can-a-program-delete-its-own-executable – GetFree Jul 10 '18 at 06:01

8 Answers8

28

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();
}
Community
  • 1
  • 1
gtikok
  • 1,119
  • 8
  • 18
4

Some Methods

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

st0le
  • 33,375
  • 8
  • 89
  • 89
  • great article, "Solution for XP+" is really awesome – Andrey Aug 11 '10 at 09:44
  • New links: [Self-deleting Executables](https://web.archive.org/web/20171109141000/http://www.catch22.net/tuts/self-deleting-executables) and [Self deleting executables](https://blogorama.nerdworks.in/selfdeletingexecutables/) – GetFree Sep 24 '20 at 02:02
4

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.

janm
  • 17,976
  • 1
  • 43
  • 61
3

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

dmckee --- ex-moderator kitten
  • 98,632
  • 24
  • 142
  • 234
user209462
  • 65
  • 3
  • 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. – dmckee --- ex-moderator kitten Aug 11 '10 at 14:44
  • 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 '18 at 13:35
0

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

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
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.

0xvpr
  • 1
  • 1
  • 2
-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).

SpliFF
  • 38,186
  • 16
  • 91
  • 120
  • If it is executed in memory, why can't I (in windows) delete the executable if the program is running? – devoured elysium Aug 11 '10 at 09: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. –  Aug 11 '10 at 09:37
  • Ah, I see. That was mainly what I thought would happen. – devoured elysium Aug 11 '10 at 09: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 '10 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 '10 at 10:25
  • The situation in unix is also not a simple as *"places the program in memory"* either as mapping may be used, but the entry in the filesystem *may* be deleted while the file is running without adversely effecting the operation of the program. Thus in unix the only requirement is that the program know where it's own executable is on disk, which is usually but not always `argv[0]`. – dmckee --- ex-moderator kitten Aug 11 '10 at 14:42