It is just missing the correct malloc calls. Fix correct malloc call - malloc

The following function tries to make a list of n nodes (backward direction for
simplicity), in each node a vector of dimension n suitably initialized. It is just missing
the correct malloc calls.
listnode *alloc(int n)
{
listnode *head = NULL;
for (int i = 0; i < n; i++) {
listnode *p;
p->vec.dim = n;
for (int j = 0; j < n; j++) {
p->vec.a[j] = 1.0;
}
p->next = head;
head = p;
}
return head;
}

Related

Treat Mmap as volatile in Rust

I am trying to monitor a binary file containing single 32 bit integer. I mapped the file into memory via MmapMut and read in a forever loop:
fn read(mmap: &MmapMut) {
let mut i = u32::from_ne_bytes(mmap[0..4].try_into().unwrap());
loop {
let j = u32::from_ne_bytes(mmap[0..4].try_into().unwrap());
if j != i {
assert!(false); // this assert should fail, but it never does
i = j;
}
}
}
However, compiler seems to optimise the loop away assuming neither i or j can ever change.
Is there a way to prevent this optimisation?
You can use MmapRaw with read_volatile().
fn read(mmap: &MmapRaw) {
let mut i = unsafe { mmap.as_ptr().cast::<u32>().read_volatile() };
loop {
let j = unsafe { mmap.as_ptr().cast::<u32>().read_volatile() };
if j != i {
assert!(false);
i = j;
}
}
}

wgsl for loop syntax

i found the following example on https://www.w3.org/TR/WGSL/#for-statement
for(var i: i32 = 0; i < 4; i++) {
if a == 0 {
continue;
}
a = a + 2;
}
but my code doesn't work
// shader.wgsl
struct MarchOutput {
steps: i32;
depth: f32;
minimum_distance: f32;
hit: bool;
};
fn march(
point: vec3<f32>, direction: vec3<f32>,
max_steps: i32, max_shading_distance: f32, min_hit_distance: f32
) -> MarchOutput {
var out = MarchOutput ( 0, 0.0, max_shading_distance, false );
for (out.steps=0; out.depth < max_shading_distance && out.steps < max_steps; out.steps++) {
var current_position: vec3<f32> = point + direction * depth;
var current_distance: f32 = SDF(current_position);
if (abs(current_distance) < min_hit_distance) {
out.hit = true;
break;
}
out.minimum_distance = min(out.minimum_distance, current_distance);
out.depth += current_distance;
}
return out;
}
error:
Shader 'shader' parsing error: expected operation ('='), found '+'
┌─ wgsl:95:88
95 │ for (out.steps=0; out.depth < max_shading_distance && out.steps < max_steps; out.steps++) {
expected operation ('='), found '+'
what am i doing wrong here ?
the latest released version does not has the increment and decrement operators or the += (and other similar operators). However, the naga master branch has the commits merged so in future releases these operators will work.
For now use i=i+1

Rust thread 'main' has overflowed its stack

I'm trying to re-implement this C code:
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#define ROWS 100000
#define COLS 10000
int twodarray[ROWS][COLS];
int main() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
twodarray[i][j] = rand();
}
}
int64 sum = 0;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
sum += twodarray[i][j];
}
}
}
So, after a lot of trial and error I've come up with Rust code that at least compiles
extern crate rand;
const ROWS: usize = 100000;
const COLS: usize = 10000;
fn main() {
let mut twodarray: [[u128; COLS]; ROWS] = [[0; COLS]; ROWS];
for i in 0..ROWS {
for j in 0..COLS {
twodarray[i][j] = rand::random::<u8>() as u128;
}
}
let mut sum: u128 = 0;
for k in 0..ROWS {
for j in 0..COLS {
sum += twodarray[k][j] as u128;
}
}
println!("{}", sum);
}
But when I compile and execute it, I get the following error message: thread 'main' has overflowed its stack. To be honest, I have absolutelly no idea why this is happening. I'm currently learning rust, but there is not a lot of information on 2d arrays online... I DO NOT WANT TO USE VECTOR. This exercise is specifically aimed on arrays.
EDIT:
After reading the accepted answear, I've come up with Rust code that outputs expected results:
extern crate rand;
const ROWS: usize = 100000;
const COLS: usize = 10000;
fn main() {
// let mut twodarray: Box<[[u8; COLS]; ROWS]> = Box::new([[0; COLS]; ROWS]);
// for i in 0..ROWS {
// for j in 0..COLS {
// twodarray[i][j] = rand::random::<u8>();
// }
// }
// let mut sum: u32 = 0;
// for k in 0..ROWS {
// for l in 0..COLS {
// sum += twodarray[k][l] as u32;
// }
// }
let mut twodarray: Box<[[u8; ROWS]; COLS]> = Box::new([[0; ROWS]; COLS]);
for i in 0..COLS {
for j in 0..ROWS {
twodarray[i][j] = rand::random::<u8>();
}
}
let mut sum: u32 = 0;
for k in 0..COLS {
for l in 0..ROWS {
sum += twodarray[k][l] as u32;
}
}
println!("{}", sum);
}
This two-dimensional array is huge. Rust tries to allocate it on the stack (that's the way arrays in Rust work).
You explicitly wrote you didn't want to use vectors, but in reality vectors are allocated on the heap, so you wouldn't have such a problem with them. It's good to keep that in mind.
If you insist on using arrays, maybe put them in a Box, so that they go to the heap?
That's not a Rust-specific problem. Stacks are generally a lot more limited, compared to the heap, usually up to a few megabytes. In some other languages, such as Java, arrays are allocated on the heap, but that doesn't mean there is no similar stack size limit there as well.

Merge sort code not giving desired output in rust

I was trying to do a merge sort code in rust.but its not giving the desired output.I tried to debug it for a while but sadly i couldnt find where the error is.
Here is one in Rust Playground.Can you please debug it?
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=25eef03b3d421cc2ae70c3c8a1bb69cb
fn main() {
let mut vec: Vec<u32> = vec![5,7,1,1,3,8,4,4,3,2,1,8,4,9];
let len = vec.len();
let left_index: usize = 0;
let right_index: usize = len - 1;
divide(&mut vec, left_index, right_index);
println!("{:?}",vec);
}
fn divide(mut vec: &mut Vec<u32>, left_index: usize, right_index: usize){
if right_index > left_index {
let middle_index = (left_index + right_index)/2;
divide(&mut vec, left_index, middle_index);
divide(&mut vec, middle_index + 1, right_index);
sort_and_merge(&mut vec, left_index, right_index, middle_index)
}
}
fn sort_and_merge(vec: &mut Vec<u32>, left_index: usize, right_index: usize, middle_index: usize){
let mut vec_left: Vec<u32> = vec![];
let mut vec_right: Vec<u32> = vec![];
for i in left_index..= middle_index{
vec_left.push(vec[i]);
}
for i in (middle_index+1)..= right_index{
vec_right.push(vec[i]);
}
let mut i = 0; // i for vec_left
let mut j = 0; // j for vec_right
let mut k = left_index;
while i < (middle_index - left_index + 1) && j < (right_index - middle_index) {
if vec_left[i] > vec_right[j]{
vec[k] = vec_right[j];
j += 1;
k += 1;
}
else{
vec[k] = vec_left[i];
i += 1;
k += 1;
}
}
while i < vec_left.len(){
vec[k] = vec_left[i];
i += 1;
k += 1;
}
while j < vec_right.len(){
vec[k] = vec_left[j];
j += 1;
k += 1;
}
}
Quoting the code in question:
let mut j = 0; // j for vec_right
...
while j < vec_right.len(){
vec[k] = vec_left[j];
j += 1;
k += 1;
}
In the last part, it seems that you'd want to use vec_right[j].

Memory leak in a Node.js extension written in Rust

I'm writing a Node.js extension in Rust. I called this toy library from C, checked it with Valgrind and no memory leak was found.
I called the same library from Python and Ruby, running in an infinite loop, and see no sign of a memory leak. (I can not post the picture due to insufficient reputation here).
When the same library is called from Node.js, the memory usage seems to increase with time:
The unit of time is the cycle of loop, not a real time.
Here is the Rust code:
#[repr(C)]
pub struct Matrix {
m: Vec<Vec<f64>>,
}
#[no_mangle]
pub extern "C" fn matrix_new(nrow: usize, ncol: usize) -> *mut Matrix {
let mut m = Vec::new();
for _ in 0..(nrow) {
let mut n = Vec::new();
for _ in 0..(ncol) {
n.push(0.0);
}
m.push(n);
}
Box::into_raw(Box::new(Matrix { m: m }))
}
#[no_mangle]
pub extern "C" fn matrix_free(matrix: *mut Matrix) {
if matrix.is_null() {
return
}
unsafe { Box::from_raw(matrix); }
}
Here is the original Node.js code:
var ref = require('ref');
var ffi = require('ffi');
var c_matrix = ref.types.void;
var c_matrix_ptr = ref.refType(c_matrix);
var libmatrix = ffi.Library('./target/release/libmatrix.so', {
'matrix_new': [ c_matrix_ptr, ['size_t', 'size_t']],
'matrix_get': [ 'double', [ c_matrix_ptr, 'size_t', 'size_t']],
'matrix_set': [ 'double', [ c_matrix_ptr, 'size_t', 'size_t', 'double']],
'matrix_free': [ 'void', [ c_matrix_ptr ]]
});
var matrix = function(nrow, ncol) {
"use strict";
var matrix = libmatrix.matrix_new(nrow, ncol);
Object.defineProperty(this, '_matrix', {
value: matrix,
writeable: false
});
return this;
};
matrix.prototype.get = function(row, col) {
"use strict";
return libmatrix.matrix_get(this._matrix, row, col);
};
matrix.prototype.set = function(row, col, value) {
"use strict";
libmatrix.matrix_set(this._matrix, row, col, value);
};
matrix.prototype.free = function() {
"use strict";
libmatrix.matrix_free(this._matrix);
};
module.exports = matrix;
if (!module.parent) {
while (true) {
var m = new matrix(3, 3);
m.free();
m = null;
delete global.m;
global.gc();
console.log(process.memoryUsage().rss);
}
}
Some information:
OS: Debian GNU/Linux (Jessie)
Node.js: 7.2.0
node-gyp: 7.2.0
ffi: 2.2.0
ref: 1.3.3
Rust: 1.13.0
I re-wrote the same library in C:
typedef struct Matrix {
size_t nrow;
size_t ncol;
double** mtx;
} Matrix;
void* matrix_new(size_t row, size_t col) {
Matrix* m = malloc(sizeof(Matrix));
m->nrow = row;
m->ncol = col;
m->mtx = malloc(m->nrow * sizeof(double*));
for (int i = 0; i < m->nrow; i++) {
*((m->mtx)+i) = (double*) malloc(m->ncol * sizeof(double));
}
for (int i = 0; i < m->nrow; i++) {
for (int j = 0; j < m->ncol; j++) {
m->mtx[i][j] = 0.0;
}
}
return (void*) m;
}
void matrix_free(void* m) {
if (m == NULL) {
return;
}
double** ptr = ((Matrix*) m)->mtx;
for (int i = 0; i < ((Matrix*) m)->nrow; i++) {
free((void*) (ptr[i]));
}
free((void*) ((Matrix*) m)->mtx);
free((void*) m);
}
I also changed the version of Node from 7.2.0 to 7.3.0. Here is the memory usage of the Node.js module with both C and Rust implementation:
I tried a no-op library without changing the Node.js code, finding something surprising myself:

Resources