How to make the code displays its own source code in hexadecimal as output? — C Programming Language

Iheb Yahyaoui
2 min readNov 3, 2021

Wait is it even possible ?

Well in C everything is possible !

There are many methodes to make a C program print it’s own source code, but in this article, we will focus only in one method.
So, you should have basic knowledge of pointers in C to understand the how the code works.

Pointers

The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer.[1]
But here we will only focus in pointers to functions which stores the code of the function he’s pointed to.

Step 1: Writing main.c

First of all we need to create our main function as its shown down:

#include <stdio.h>
int main(void)
{
return(0);
}

Step 2: Using Pointers

Secondly, we need to declare a pointer which pointes to the main function and use a loop to show the whole code.

#include <stdio.h>
int main(void)
{
unsigned char *pointer; // pointer declaration
unsigned int i = 0; // int declartion toiterate the pointer
pointer = (unsigned char *)main; // a pointer to the main function
while(pointer[i])
{
printf("%x\n",pointer[i]);
i++;
}
return(0);
}

Step 3: Let the fun begin !

Let’s compile the code using gcc compiler as shown down:

gcc -std=gnu89 main.c -o main

Then let’s run our program.

The result of the program

Webography

[1] : https://www.javatpoint.com/c-pointers

Thank you for reading.

If you have any questions, feel free to comment and, if you would like to see more like these articles please clap your hands 👏👏👏

--

--

Iheb Yahyaoui

Software Developer/ Holbertoon School Student / Blogger / Bibliophile ! LinkedIn: https://www.linkedin.com/in/ihebyh/