Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nyinyithann
Created February 13, 2019 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyinyithann/4db3d74b14244974ae9829a1b22061c7 to your computer and use it in GitHub Desktop.
Save nyinyithann/4db3d74b14244974ae9829a1b22061c7 to your computer and use it in GitHub Desktop.
A simple freestanding program using libc
#![feature(start)]
#![no_std]
extern crate libc;
use core::panic::PanicInfo;
use libc::{c_char, c_int, c_void, size_t};
extern "C" {
fn malloc(size: size_t) -> *mut c_void;
fn free(p: *mut c_void);
fn exit(status: c_int) -> !;
fn printf(fmt: *const c_char, ...) -> c_int;
}
#[start]
fn main(argc: isize, _argv: *const *const u8) -> isize {
unsafe {
let ptr1 = malloc(32 as size_t) as *mut i32;
if ptr1 as usize == 0 {
printf("Memory not allocated.\0".as_ptr() as *const i8);
exit(0);
}
*ptr1 = 2;
let ptr2 = malloc(32 as size_t) as *mut i32;
if ptr2 as usize == 0 {
printf("Memory not allocated.\0".as_ptr() as *const i8);
exit(0);
}
*ptr2 = 5;
printf(
"%d + %d = %d\0".as_ptr() as *const i8,
*ptr1,
*ptr2,
*ptr1 + *ptr2,
);
free(ptr1 as *mut c_void);
free(ptr2 as *mut c_void);
}
0
}
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {}
}
@nyinyithann
Copy link
Author

nyinyithann commented Feb 13, 2019

cargo.toml

[package]
name = "libc"
version = "0.1.0"
authors = ["nyinyithann nyinyithann@gmail.com"]
edition = "2018"

[profile.dev]
panic = "abort"

[profile.release]
panic = "abort"

[dependencies]
libc = { version = "0.2.48", default-features = false }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment