Having trouble figuring out this segmentation fault - c

I'm sure the mistake is obvious, but I sure am having trouble finding it.
Basically I am trying to make a chessboard via 2D array. I am testing its functionality via 8 queens test... it is not functional.
Somehow one of my integer values is getting out of whack, as gdb shows:
....
(gdb) cont
Continuing.
Program received signal SIGSEGV, Segmentation fault.
0x080487f8 in diagnols (PARAMETER_ONE=0, PARAMETER_TWO=0) at eq1.c:77
77 if (key->board[abc][bcd] == 1) {
(gdb) print abc
4424 // "SHOULD BE" ONE
(gdb) print bcd
4424 // "SHOULD BE" ONE
(gdb) backtrace
#0 0x080487f8 in diagnols (PARAMETER_ONE=0, PARAMETER_TWO=0) at eq1.c:77
#1 0x08048873 in check (param1=0, param2=0) at eq1.c:91
#2 0x08048510 in recur (DEPTH=0, WIDTH=0) at eq1.c:99
#3 0x08048919 in main () at eq1.c:152
(gdb)
Then here is diagnols(...), which is in:
int recur(struct chessboard* key, int DEPTH, int WIDTH) {
/* other functions above diagnols(...) */
diagnols(...):
int diagnols(int PARAMETER_ONE, int PARAMETER_TWO) { // returns 0 if good
int abc = 0;
int bcd = 0;
int counter = 0; // keeps track of conflicting piece occurrences
// OTHER CHECKS FIRST... DELETED TO SAVE ROOM
// checkign diagnol down and to the left
abc = PARAMETER_ONE+1;
bcd = PARAMETER_TWO-1;
while ( (abc>=0)&&(bcd>=0) ) {
if (key->board[abc][bcd] == 1) {
counter++;
} abc++;
bcd--;
}
// ERROR IN THIS PART
// checking diagnol down and to the right
abc = PARAMETER_ONE+1;
bcd = PARAMETER_TWO+1;
while ( (abc>=0)&&(bcd>=0) ) {
if (key->board[abc][bcd] == 1) { // ERROR
counter++;
} abc++;
bcd++;
}
return counter;
}
And diagnols(...) is invoked in recur(...) in the below function:
int check(int param1, int param2) { // if okay returns 2
// other functions
d = diagnols(param1, param2);
int total = 0;
total = (h + v + d); // if okay, equals 2
return total;
}
For good measure here is my struct:
struct chessboard {
int board[7][7];
};
And main:
int main() {
struct chessboard* master = malloc(sizeof(struct chessboard));
/* i set the board to zero here. used calloc() before */
recur(master, 0, 0);
// stuff
}
And yes, I realize diagnol isn't spelled diagonal ;)

while ( (abc>=0)&&(bcd>=0) ) {
if (key->board[abc][bcd] == 1) { // ERROR
counter++;
} abc++;
bcd++;
}
It seems that the condition is going to always be true since you are increasing both indexes.
Did you mean < some limit instead?

Related

Why does my program keep getting stuck while running the mandelbrot brainf*** program?

I wanted to improve my C skills, so I search some program's ideas.
Someone propose to create a simple Brainf*** interpreter and then a compiler. So here I am.
I created the interpreter and it works as expected, except with the Mandelbrot program:
A mandelbrot set fractal viewer in brainfuck written by Erik Bosman
+++++++++++++[->++>>>+++++>++>+<<<<<<]>>>>>++++++>--->>>>>>>>>>+++++++++++++++[[
>>>>>>>>>]+[<<<<<<<<<]>>>>>>>>>-]+[>>>>>>>>[-]>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>[-]+
<<<<<<<+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>>+>>>>>>>>>>>>>>>>>>>>>>>>>>
>+<<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+[>>>>>>[>>>>>>>[-]>>]<<<<<<<<<[<<<<<<<<<]>>
>>>>>[-]+<<<<<<++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<+++++++[-[->>>
>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[[-]>>>>>>[>>>>>
>>[-<<<<<<+>>>>>>]<<<<<<[->>>>>>+<<+<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>
[>>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<+<<]>>>>>>>>]<<<<<<<<<[<<<<<<<
<<]>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<<<]>>>>>>>>>+++++++++++++++[[
>>>>>>>>>]+>[-]>[-]>[-]>[-]>[-]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->>>>>>>>
-<<[-<<<<<<+>>>>>>]<<<<<<[->>>>>>+<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+>>>>>>[>>>>>>
>>>]>[-]+<]]+>[-<[>>>>>>>>>]<<<<<<<<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>[-]<<<++++
+[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>->>>>>>>>>>>>>>>>>>>>>>>>>>>-<<<<<<[<<<<
<<<<<]]>>>]
I don't understand why, but my program keeps getting stuck in some sort of endless loop. I try to debug it using gdb but it's hard to find the right breakpoint in order to see why it stuck.
The program is as follows:
#include <stdio.h>
#include <stdlib.h>
// Brainfuck instructions
// > Math stuff
#define INCR '+' // +1 on current MS
#define DECR '-' // -1 on current MS
// > Memory slot stuff
#define FORW '>' // Go to next MS
#define BACK '<' // Go to previous MS
// > Logic stuff
#define SJMP '[' // Loop till current MS value is equal to zero
#define EJMP ']' // Jump to the beginning of the loop
// > I/O stuff
#define PRTC '.' // Print character with MS value as ASCII code
#define GETC ',' // Get an user input ASCII character code
typedef unsigned char byte;
// The brainfuck program struct
typedef struct {
byte *values;
int size;
int index;
byte *loops_starts;
int loop_size;
int loop_index;
} BrainfuckProgram;
void initialize(BrainfuckProgram *bfp) {
bfp->values = malloc(bfp->size * sizeof(*bfp->values));
bfp->loops_starts = malloc(bfp->size * sizeof(*bfp->loops_starts));
}
int allocate_values(BrainfuckProgram *bfp) {
byte *newMem = realloc(bfp->values, bfp->size * sizeof(byte));
if (!newMem) {
return 1;
}
bfp->values = newMem;
return 0;
}
int allocate_new_loop(BrainfuckProgram *bfp) {
byte *newMem = realloc(bfp->loops_starts, bfp->loop_size * sizeof(byte));
if (!newMem) {
return 1;
}
bfp->loops_starts = newMem;
return 0;
}
void set_value(BrainfuckProgram *bfp, byte value) {
int tempValue = value < 0 ? 255: value % 256;
*(bfp->values + bfp->index) = tempValue;
}
int get_value(BrainfuckProgram *bfp) {
return *(bfp->values + bfp->index);
}
// FILE functions
int get_file_name(int argc, char *argv[], char** fname) {
if (argc == 1) {
printf("File name is missing\n");
return 1;
}
*fname = argv[1];
return 0;
}
int get_file_size(FILE *file) {
fseek(file, 0L, SEEK_END);
int size = ftell(file);
rewind(file);
return size;
}
// Main function
int main(int argc, char *argv[]) {
// Vector part
BrainfuckProgram bfp = {
.values = NULL,
.size = 1,
.index = 0,
.loops_starts = NULL,
.loop_index = 0,
.loop_size = 0
};
initialize(&bfp);
// FILE Part
char* fname = NULL;
int error = get_file_name(argc, argv, &fname);
if (error) {
goto exit;
}
// Create file variable
FILE *fin = NULL;
fin = fopen(fname, "r");
int size = get_file_size(fin);
// Create a char array of the right size
byte *prog = NULL;
prog = malloc(size * sizeof(*prog));
// Read 1 byte size times
fread(prog, 1, size, fin);
for (int i = 0; i < size; i++) {
byte current = *(prog+i);
switch (current) {
case INCR:
set_value(&bfp, get_value(&bfp) + 1);
break;
case DECR:
set_value(&bfp, get_value(&bfp) - 1);
break;
case FORW:
// if index+1 == size then we are at the
// last element of the vector cause
// size = index - 1
if (bfp.index+1 == bfp.size) {
bfp.size++;
int error = allocate_values(&bfp);
if (error) {
printf("an error occured while forwarding pointer");
goto close;
}
}
bfp.index++;
break;
case BACK:
// bfp.index == 0 then !bfp.index == true
if (!bfp.index) {
printf("can go back from index 0\n");
goto close;
}
bfp.index--;
break;
case SJMP:
if (bfp.loop_index == bfp.size) {
bfp.loop_size++;
int error = allocate_new_loop(&bfp);
if (error) {
printf("an error occured while forwarding pointer");
goto close;
}
}
bfp.loop_index++;
*(bfp.loops_starts + bfp.loop_index) = i;
break;
case EJMP:
if (bfp.loop_index == -1) {
printf("cannot go back");
goto close;
}
if (get_value(&bfp) != 0) {
i = *(bfp.loops_starts + bfp.loop_index);
} else {
bfp.loop_index--;
}
break;
case PRTC:
printf("%c", get_value(&bfp));
break;
case GETC:
; // Semicolon here because of the label error
byte buf;
scanf("%c", &buf);
set_value(&bfp, buf);
break;
}
}
close:
fclose(fin);
exit:
;
return 0;
}
I'd like to have some C related advice on what I have done wrong too.
The Mandelbrot program takes a decent time to run on a good interpreter. Yours, well, it isn't that good. That's why it "hangs" at the start.
Some good ideas that you had, performance-wise:
precalculating loops
Some bad ideas, performance-wise:
Using abstracted allocation functions instead of calling realloc
using scanf and printf instead of getchar and putchar
Some odd things that you did:
Manually truncating an unsigned char when wraparound is implicit
checking if an unsigned char is less than 0
using *(x + y) syntax instead of array indexing x[y]
I don't think you actually use those precalculated loops, if you do then probably not correctly
You also probably create a new precalculated loop every time you go over the loop again
Using the get_value and set_value functions instead of pointers (this will be a performance issue if you don't compile with optimizations)
A couple suggestions:
Try to avoid calling functions when you don't need to as much as possible.
Write a BrainFuck->C compiler using this reference.
On second thought, maybe you should try to debug this program instead.
You may also use my interpreter as a reference if you're OK with GPLv3. Note that it doesn't precalculate loops.

Segmentation fault on deleting an element after searching it in a heap

The following code deletes an element x from a heap after searching it linearly in the heap
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MaxSize 100001
struct minheap {
long int a[MaxSize];
int end;
};
void minHeapify(struct minheap *h, int i) {
int largest;
long int temp;
int l=2*i+1;
int r=2*i+2;
largest=i;
if(l<=(h->end) && (h->a[l])<(h->a[i]))
largest=l;
if(r<=(h->end) && (h->a[r])<(h->a[largest]))
largest=r;
if(largest!=i) {
temp=h->a[i];
h->a[i]=h->a[largest];
h->a[largest]=temp;
minHeapify(h,largest);
}
}
int main() {
long int x,i=0,temp=0;
int N;
int type;
scanf("%d",&N);
struct minheap h;
h.end=-1;
while(N--) {
scanf("%d",&type);
if(type==1) {
scanf("%ld",&x);
h.end=h.end+1;
h.a[h.end]=x;
i=h.end;
while(i>0 && h.a[(i-1)/2]>h.a[i]) { //fix minheap on insertion
temp = h.a[(i-1)/2];
h.a[(i-1)/2]=h.a[i];
h.a[i]=temp;
i=(i-1)/2;
}
}
else if(type==2) {
scanf("%ld",&x);
for(i=0;i<=h.end;i++) {
if(x == h.a[i])
break;
}
h.a[i]=h.a[h.end];
h.end=h.end-1;
if(i!=(h.end+1))
minHeapify(&h,i);
}
else if(type==3) {
printf("%ld\n",h.a[0]);
}
}
return 0;
}
But the following test case gives segmentation fault as:
Program terminated with signal SIGSEGV, Segmentation fault.
#0 main () at solution.c:59
59 if(x == h.a[i])
#0 main () at solution.c:59
The entire test case can be found on this link:
https://hr-testcases-us-east-1.s3.amazonaws.com/15379/input04.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1547134261&Signature=D%2B39%2BHr%2F4lRFV%2BetxFwnGWm1iac%3D&response-content-type=text%2Fplain
Why is this segmentation fault occurring?
Given the error message,
> Program terminated with signal SIGSEGV, Segmentation fault.
> #0 main () at solution.c:59 59 if(x == h.a[i])
> #0 main () at solution.c:59
...the value i in the expression: if(x == h.a[i]) is probably out of bounds. This leads to undefined behavior, which in some cases might seem to work, other might lead to a segmentation fault.
Look at this line for a possible the solution:
for(i=0;i<=h.a[h.end];i++)
What is the value of a.end at the time this expression is called?
There is also a potential for problems here:
while(i>0 && h.a[(i-1)/2]>h.a[i])
Where the expression: (i-1)/2 is integer division, and will skip values.
I see a few problems in your code to delete an item:
for(i=0;i<=h.end;i++) {
if(x == h.a[i])
break;
}
h.a[i]=h.a[h.end];
h.end=h.end-1;
if(i!=(h.end+1))
minHeapify(&h,i);
First, if an item with the value you entered is not found, you're going to have trouble because i > h.end. You'll end up either indexing off the end of the array, or deleting the last item.
More importantly, you're not handling the case where the item you replace it with is smaller than the parent. For example, consider this heap:
1
6 2
7 8 3
If you delete the node with value 7, the value 3 replaces it:
1
6 2
3 8
That's not a valid heap. You have to move the 3 up in the heap to create:
1
3 2
6 8
The key here is that if the item you're replacing is in a different subtree than the last item in the heap, it's possible that the replacement node will be smaller than the parent of the replaced node.
So your code has to do this:
h.a[i] = h.a[h.end];
h.end = h.end-1;
// here you have to:
// if (h.a[i] < parentOf(h.a[i]))
// move it up the heap
// else
// minHeapify(&h, i);

Initializing an array of structure in C

I'm using the LXLE 14.04 distribution of Linux. I want to write a C program to read commands, interpret and perform them. I'd like the program to be efficient, and I do not want to use a linked list. The commands are operations on sets. Each set can contain any of the values from 0 through 127 inclusive. I decided to represent a set as an array of characters, containing 128 bits. If bit at position pos is turned on then the number pos is in the set and if the bit at position pos is turned off then the number pos is not present in the set. For example, if the bit at position 4 is 1, then the number 4 is present in the set, if the bit at position 11 is 1 then the number 11 is present in the set.
The program should read commands and interpret them in a certain way. There are a few commands: read_set, print_set, union_set, intersect_set, sub_set and halt.
For example, the command read_set A,1,2,14,-1 in the terminal will cause the reading of values of the list into the specified set in the command. In this case the specified set in the command is A. The end of the list is represented by -1. So after writing this command, the set A will contain the elements 1,2,14.
This is what I have so far. Below is the file set.h
#include <stdio.h>
typedef struct
{
char array[16]; /*Takes 128 bits of storage*/
}set;
extern set A , B , C , D , E , F;
This is the file main.c
#include <stdio.h>
#include "set.h"
#include <string.h>
#include <stdlib.h>
set A , B , C , D , E , F; /*Variable definition*/
set sets[6];
/*Below I want to initialize sets so that set[0] = A set[1] = B etc*/
sets[0].array = A.array;
sets[1].array = B.array;
sets[2].array = C.array;
sets[3].array = D.array;
sets[4].array = E.array;
sets[5].array = F.array;
void read_set(set s,char all_command[])
{
int i, number = 0 , pos;
char* str_num = strtok(NULL,"A, ");
unsigned int flag = 1;
printf("I am in the function read_set right now\n");
while(str_num != NULL) /*without str_num != NULL get segmentation fault*/
{
number = atoi(str_num);
if(number == -1)
return;
printf("number%d ",number);
printf("str_num %c\n",*str_num);
i = number/8; /*Array index*/
pos = number%8; /*bit position*/
flag = flag << pos;
s.array[i] = s.array[i] | flag;
str_num = strtok(NULL, ", ");
if(s.array[i] & flag)
printf("Bit at position %d is turned on\n",pos);
else
printf("Bit at position %d is turned off\n",pos);
flag = 1;
}
}
typedef struct
{
char *command;
void (*func)(set,char*);
} entry;
entry chart[] = { {"read_set",&read_set} };
void (*getFunc(char *comm) ) (set,char*)
{
int i;
for(i=0; i<2; i++)
{
if( strcmp(chart[i].command,comm) == 0)
return chart[i].func;
}
return NULL;
}
int main()
{
#define PER_CMD 256
char all_comm[PER_CMD];
void (*ptr_one)(set,char*) = NULL;
char* comm; char* letter;
while( (strcmp(all_comm,"halt") != 0 ) & (all_comm != NULL))
{
printf("Please enter a command");
gets(all_comm);
comm = strtok(all_comm,", ");
ptr_one = getFunc(comm);
letter = strtok(NULL,",");
ptr_one(sets[*letter-'A'],all_comm);
all_comm[0] = '\0';
letter[0] = '\0';
}
return 0;
}
I defined a command structure called chart that has a command name and function pointer for each command. Then I have created an array of these
structures which can be matched within a loop.
In the main function, I've created a pointer called ptr_one. ptr_one holds the value of the proper function depending on the command entered by the user.
The problem is, that since user decides which set to use,I need to represent the sets as some variable, so that different sets can be sent to the function ptr_one. I thought about
creating an array in main.c like so
set sets[6];
sets[0] = A;
sets[1] = B;
sets[2] = C;
sets[3] = D;
sets[4] = E;
sets[5] = F;
And then call the function ptr_one in the main function like this ptr_one(sets[*letter-'A'] , all_command).
That way, I convert my character into a set.
The problem is that while writing the above code I got the following compile error:
error: expected ���=���, ���,���, ���;���, ���asm��� or ���attribute��� before ���.��� token
I also tried the following in the file main.c
sets[0].array = A.array;
sets[1].array = B.array;
sets[2].array = C.array;
sets[3].array = D.array;
sets[4].array = E.array;
sets[5].array = F.array;
But I got this compile error expected ���=���, ���,���, ���;���, ���asm��� or ���attribute��� before ���.��� token
I know similar questions have been asked, by they don't seem to help in my
specific case. I tired this set sets[6] = { {A.array},{B.array},{C.array},{D.array},{E.array},{F.array} } too but it did not compile.
What's my mistake and how can I initialize sets so that it holds the sets A though F?

Error when creating lua table from inside the c api

I have an A* algorithm in C, intended to be used from Lua. Now, the A* itself works fine but for some weird reason, when I call it from Lua, there's a weird error that pops out when any one of the argument functions (Neighbours) creates a table. Creating a table in C works fine.
There are 2 versions of the library - 1st one called the script directly from C in the 'main' function, and creating tables from Lua worked smoothly. 2nd one is compiled to dll and loaded by the script which crashes when making tables. Why, I have no idea.
I've already tried allocating all my memory inside C and passing lightuserdata but it made no difference.
I have other .dlls compiled on the same machine which don't replicate this error.
C LIBRARY
int run(lua_State *L)
/*
1: string from,
2: string to,
3: string[] Neighbours(string of),
4: int Cost(string from, string to, string dest),
5: int Heuristic(string from, string to, string dest)
*/
{
char flag = 0;
HE = HE ? HE : Heap_Alloc(200);
Heap_Clear(HE);
// create the HASHtable
lua_createtable(L,1,300);
// 6 - HASHtable (string -> {int cost,string Self,string parent})
// get Heuristic(0,from,to)
lua_pushvalue(L,5);
lua_pushstring(L,0);
lua_pushvalue(L,1);
lua_pushvalue(L,2);
lua_call(L,3,1);
{
// 7 - Heuristic(0,from,to)
Heap_val_t hp = {lua_tointeger(L,7), lua_tostring(L,1)};
Z q;
// HASH[from] = {cost=Heuristic, self=from, parent=nil}
lua_pushvalue(L,1);
lua_newuserdata(L,sizeof(struct g));
q = lua_touserdata(L,-1);
q->_cost = lua_tointeger(L,7);
q->_self = lua_tostring(L,1);
q->_parent = 0;
lua_rawset(L,6);
// pop Heuristic(0,from,to) (6)
lua_pop(L,1);
Heap_Push_macro(HE, hp);
while (!Heap_Empty(HE))
{
int i=1;
hp = Heap_Top(HE);
Heap_Pop_macro(HE);
// push Neighbours(Self) on the stack
lua_pushvalue(L,3);
lua_pushstring(L,hp._self);
lua_call(L,1,1); // ALLOCATING TABLE INSIDE THIS GENERATES THE ERROR
while(1)
{
// 7 - neighbours table[]
// push neighbours[i]
lua_rawgeti(L,-1,i);
// check if we got to the end of neighbours
if (!lua_isstring(L,-1))
{
lua_pop(L,1);
break;
}
{
// 8 - neighbours[i]
int cost,heur;
// get HASH[hp.self].cost and pop from stack
lua_pushstring(L,hp._self);
lua_rawget(L,6);
q = lua_touserdata(L,-1);
cost = q->_cost;
lua_pop(L,1);
// call Cost(hp.self,*neighbours,to)
lua_pushvalue(L,4);
lua_pushstring(L,hp._self);
lua_pushvalue(L,8);
lua_pushvalue(L,2);
lua_call(L,3,1);
// add it to cost and remove from stack
cost += lua_tointeger(L,-1);
lua_pop(L,1);
// get Heuristic(hp._obj, *neighbours, to) and pop it
lua_pushvalue(L,5);
lua_pushstring(L,hp._self);
lua_pushvalue(L,8);
lua_pushvalue(L,2);
lua_call(L,3,1);
heur = lua_tointeger(L,-1);
lua_pop(L,1);
// get HASH[*neighbours]
lua_pushvalue(L,8);
lua_rawget(L,6);
q = lua_touserdata(L,-1);
if (!q || q->_cost > cost+heur)
{
Heap_val_t y = {cost+heur, lua_tostring(L,8)};
Heap_Push_macro(HE, y);
// HASH[*neighbours] = {cost=cost, self=*neighbours, parent=hp.self}
lua_pushvalue(L,8);
lua_newuserdata(L,sizeof(struct g));
q = lua_touserdata(L,-1);
q->_cost = cost;
q->_self = lua_tostring(L,8);
q->_parent = hp._self;
lua_rawset(L,6);
}
// remove 10
lua_pop(L,1);
// 9
}
// remove neighbours[i]
lua_pop(L,1);
i++;
// 8
}
// remove neighbours[]
lua_pop(L,1);
// 7
lua_pushstring(L,hp._self);
if (lua_equal(L,-1,2))
{
flag = 1;
// pop the string
lua_pop(L,1);
break;
}
lua_pop(L,1);
}
// 7 - return path table
lua_createtable(L,1,1);
if (flag)
{
int i=1,j;
while(1)
{
Z g;
lua_pushvalue(L,2);
lua_rawget(L,6);
g = lua_touserdata(L,-1);
if (!g->_parent)
{
lua_pop(L,1);
break;
}
lua_pushstring(L,g->_parent);
lua_replace(L,2);
lua_pushstring(L,g->_self);
lua_rawseti(L,7,i++);
lua_pop(L,1);
}
// reverse the table
for (j=1, i--; i-j > 0; i--,j++)
{
lua_rawgeti(L,7,j);
lua_rawgeti(L,7,i);
lua_rawseti(L,7,j);
lua_rawseti(L,7,i);
}
}
}
// replace HASH with return table
lua_replace(L,6);
return 1;
}
LUA SCRIPT
require 'astar'
function X(z)
local a = z:find'[? ]'
return tonumber(z:sub(1,a))
end
function Y(z)
local a = z:find'[? ]'
return tonumber(z:sub(a))
end
m,n = {-1,-1,-1,0,0,1,1,1},{-1,0,1,-1,1,-1,0,1}
function neighbours(of)
print('neighbours',of)
local x,y = X(of),Y(of)
-- local r = {} -- creating a table from inside the C api crashes
local r = 0
for i=1,#m do
local nx,ny = x+m[i],y+n[i]
--table.insert(r,nx..' '..ny)
end
return r
end
function cost(from,to,dest)
return 1
end
function heuristic(from,to,dest)
local x1,y1,x2,y2 = X(to),Y(to),X(dest),Y(dest)
return math.abs(x1-x2)+math.abs(y1-y2)
end
print{} -- making tables before C api call..
r = astar.run('0 0','1 0', neighbours, cost, heuristic)
print{} -- ..or after doesn't crash
print('r',r)
if r then
print(#r)
for i,j in pairs(r) do
print(i,j)
end
end
I finally figured it out: Lua doesn't like pendrives.
When I offloaded the vc++ project and build it from my hard drive, everything went right.
Kids, don't build Lua libraries on a pendrive.

ncurses program crashes on anything other than PuTTY

I have an older ncurses-based program that does some simple IO on a few files (i.e.: setup program). However, from a terminal different from PuTTY, it crashes with SIGBUS
Program received signal SIGBUS, Bus error.
0x00000000004028b1 in fDisplay (ptr=Variable "ptr" is not available.
) at file_cpy.c:676
676 sprintf(p, " %-36s ", (*ptr)->datainfo.option);
(gdb) where
#0 0x00000000004028b1 in fDisplay (ptr=Variable "ptr" is not available.
) at file_cpy.c:676
#1 0x0000000000402cdb in fredraw (c=0x7fffffffe860) at file_cpy.c:696
#2 0x0000000000401996 in ls_dispatch (c=0x2020202020202020) at ds_cell.c:324
#3 0x0000000000403bf2 in main_dir (c=0x2020202020202020) at file_cpy.c:811
#4 0x0000000000403cb3 in main () at file_cpy.c:1345
(gdb) x/i $pc
0x4028b1 <fDisplay+17>: mov (%rax),%rdx
(gdb)
This happens on Linux and FreeBSD, regardless of ncurses version and 32/64bit architecture. I'm completely stumped.
fDisplay() is called here:
/*
* File redraw routine. Draws current list on screen.
*/
int fredraw (CELL * c)
{
register int row = c->srow;
dlistptr p = c->list_start;
int i = 0;
char buff[200];
if (c->ecol - c->scol)
sprintf(buff, "%*s",c->ecol - c->scol + 1, " ");
while (i <= c->erow - c->srow && p != NULL)
{
if (p == c->current) wattron(c->window,A_REVERSE);
mvaddstr (row , c->scol, fDisplay(&p));
if (p == c->current) wattroff(c->window,A_REVERSE);
row++; i++;
p = p->nextlistptr;
}
if (row <= c -> erow)
for (; row <= c -> erow ; row++)
mvaddstr(row, c->scol, buff);
wrefresh(c->window);
c -> redraw = FALSE;
return TRUE;
}
fredraw() is called here:
int main_dir(CELL *c) {
int i;
getcwd(current_path, sizeof(current_path));
strcat(current_path, "/.config.h");
load_file(current_path);
c->keytable = file_cpy_menu;
c->func_table = file_cpy_table;
c->ListEntryProc = File_Entry;
c->UpdateStatusProc = status_update;
c->redraw = TRUE;
c->ListExitProc = List_Exit;
c->ListPaintProc = fredraw;
c->srow = 3;
c->scol = 1;
c->erow = c->window->_maxy - 5;
c->ecol = c->window->_maxx - 1;
c->max_rows = c->window->_maxy;
c->max_cols = c->window->_maxx;
c->filename = "[ Config ]";
c->menu_bar = 0;
c->normcolor = 0x07;
c->barcolor = 0x1f;
init_dlist(c);
for (i = 0; config_type[i].option; i++)
insert_fdlist(c, &config_type[i]);
/*
* Go Do It
*/
do {
c->redraw = TRUE;
ls_dispatch(c);
} while (c->termkey != ESC && c->termkey != ALT_X);
return TRUE;
}
Finally, main() calls the above functions:
int main() {
CELL file_cpy = {0};
WINDOW *mainwin;
mainwin = initscr();
start_color();
setup_colors();
cbreak();
noecho();
keypad(mainwin, TRUE);
meta(mainwin, TRUE);
raw();
leaveok(mainwin, TRUE);
wbkgd(mainwin, COLOR_PAIR(COLOR_MAIN));
wattron(mainwin, COLOR_PAIR(COLOR_MAIN));
werase(mainwin);
refresh();
file_cpy.window = mainwin;
main_dir(&file_cpy);
wbkgd(mainwin, A_NORMAL);
werase(mainwin);
echo();
nocbreak();
noraw();
refresh();
endwin();
return TRUE;
}
Apparently you are calling main_dir and ls_dispatch with a pointer c initialized to 0x2020202020202020. While not completely impossible, I find it very unlikely, and it looks to me as if you're overwriting the pointer with spaces.
valgrind would probably help, or some kind of memory or stack protection check.
Why this depends on the terminal, I could not say; possibly there's some TERM-depending code (such as "allocate as many rows as there are on screen"). Anyway, that is not the bug: it's only the condition bringing the bug in the open. This kind of error is usually caused by a hard-wired constant which sometimes is exceeded by the real value (in the example above I could say "allocate 96 rows", assuming that 96 rows will always be enough for everyone; whereas a TERM with 100 rows would foil the assumption and lead to a buffer overrun).
It might also be an artifact of the debugger, seeing as how c is allocated on the stack (but I don't think so: it should be c=0x7fffsomething - at least on the systems where I checked) . Anyway, I'd repeat the test like this, by making file_cpy heap dynamic:
int main() {
CELL *file_cpy = NULL;
WINDOW *mainwin;
file_cpy = malloc(sizeof(CELL));
...
file_cpy->window = mainwin;
main_dir(file_cpy);
...
free(file_cpy); // file_cpy = NULL; // we immediately return
return TRUE;
and then I'd try and tabulate the pointer's value throughout the main_dir function, in case it's overwritten.

Resources