Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.