Dynamic List <malloc.h> free triggered a breakpoint - C Programming - c

Could someone help me with this one. I'm making BFS algorithm in C programming language, with help of dynamic lists.
This is my code.
// ConsoleApplication3.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <malloc.h>
#define n 6
typedef struct field
{
int x;
int y;
int dist;
struct field *next;
}Field;
// Get row and column number of 4 neighbours
int rows[] = { -1, 0, 0, 1 };
int cols[] = { 0, -1, 1, 0 };
Field *addToEnd(Field *lst, Field field)
{
Field *newField = (Field*)malloc(sizeof Field);
newField = &field;
newField->next = NULL;
if (!lst)
return newField;
else
{
Field *current;
for (current = lst; current->next; current = current->next);
current->next = newField;
return lst;
}
}
// Check if field is/isn't out of range
bool isValid(int row, int col)
{
return (row >= 0) && (row < n) && (col >= 0) && (col < n);
}
int BFS(int mat[][n], Field source, Field destination)
{
bool visited[n][n];
memset(visited, false, sizeof visited);
// Mark the source field as visited
visited[source.x][source.y] = true;
// Create dynamic list
Field *lst = NULL;
source.dist = 0;
// Adding the source field to the list
lst = addToEnd(lst, source);
while (lst)
{
// Getting first element in the list
Field current = *lst;
// If destination is reached then end function
if (current.x == destination.x && current.y == destination.y)
return current.dist;
// Delete first element of the list
Field *toDelete;
toDelete = lst;
lst = lst->next;
free(toDelete);
for (int i = 0; i < 4; i++)
{
int row = current.x + rows[i];
int col = current.y + cols[i];
// If adjacent field is valid, has path and isn't visited add it to the list
if (isValid(row, col) && mat[row][col] == 0 && !visited[row][col])
{
visited[row][col] = true;
Field adjField = { row, col, current.dist + 1 };
lst = addToEnd(lst, adjField);
}
}
}
// Return -1 if destination can't be reached
return -1;
}
int main()
{
int mat[n][n] =
{
{ 0, 0, 0, 0, 0, 0 },
{ 0, 1, 1, 1, 1, 0 },
{ 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 0 },
{ 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 0 }
};
Field start = { 1, 0 }, end = { 5, 5 };
int number = BFS(mat, start, end);
if (number != -1)
printf("%d\n", number);
else
printf("Destination can't be reached\n");
return 0;
}
Everything except part of code which need to delete first element of list is working. The problem is with free function.
https://i.stack.imgur.com/QpK1j.png
https://i.stack.imgur.com/HXp8d.png
Does anyone have an idea what could be possible wrong with this and how can I fix it?

Related

Copy array's data with memmove function

I wrote my implementation of vector ( dynamicly growing array) for integer type. And I was faced with a problem when using memmove and memcpy functions for data reallocation goals. Memmmove and memcpy functions work as not expected. So i replaced it with for and now it works properly. But what is the why memove works this way ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct vector {
int v_size;
int v_length;
int* v_data;
} vector;
typedef vector *vect;
vect
new_vector(int size) {
vect tmp = (vector*)malloc(sizeof(vector));
tmp->v_size = size;
tmp->v_length = 0;
tmp->v_data = (int*)malloc(sizeof(int) * size);
return tmp;
}
void
add_velem(vect tmp, int elem) {
if(tmp->v_length != tmp->v_size) {
tmp->v_data[tmp->v_length] = elem;
tmp->v_length += 1;
} else {
tmp->v_size = tmp->v_size * 2;
tmp->v_length += 1;
int *new_vector = (int*)malloc(sizeof(int) * tmp->v_size);
memmove(new_vector, tmp->v_data, tmp->v_length); // GOT INPUT LIKE THIS:
// 500, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
// ALOT OF ZERO
/*
for(int i = 0; i < tmp->v_length; i++) {
new_vector[i] = tmp->v_data[i];
}*/ // BUT GOT RIGHT INPUT WHEN USING FOR. WHAT IS THE REASON?
free(tmp->v_data);
tmp->v_data = new_vector;
tmp->v_data[tmp->v_length - 1] = elem;
}
return;
}
int
get_vlength(vect tmp) {
return tmp->v_length;
}
int
get_vsize(vect tmp) {
return tmp->v_size;
}
int
get_velem(vect tmp, int elem) {
if(tmp->v_data == NULL) {
fprintf(stderr, "Index out of range!\n");
}else if(elem >= tmp->v_length) {
fprintf(stderr, "Index is out of range!\n");
return -1;
}
return tmp->v_data[elem];
}
void
delete_vector(vect tmp) {
free(tmp->v_data);
tmp->v_data = NULL;
free(tmp);
tmp = NULL;
}
int
main(void) {
vect example = new_vector(10);
printf("lenth of vector is %d\n", get_vlength(example));
add_velem(example, 500);
printf("element %d is pushed into vector\n", 500);
printf("size of vector is %d and\nlength of vector is %d\n", get_vsize(example), get_vlength(example));
int velem = get_velem(example, 0);
printf("elem 0 of vector is %d\n", velem);
for(int i = 1; i < 30; i++) {
add_velem(example, i);
}
printf("length of vector is %d now\n", get_vlength(example));
for(int i = 0; i < get_vlength(example); i++) {
printf("%d, ", get_velem(example, i));
}
delete_vector(example);
return 0;
}

Adding two polynomials in C, Abort trap: 6

I am trying to add 2 polynomials using int arrays. For example,
co1[ ] = {5, 3, 2, 0, 0, 0, ...} & ex1[ ] = {6, 2, 1, 0, 0, 0, ...} represents the polynomial 5x^6 + 3x^2 + 2x. I tried doing this in different ways but I keep getting the message "Abort trap: 6" whenever I try to use this function. Any help would be appreciated. Thank you.
void add_polynom( int co1[ ], int ex1[ ], int co2[ ], int ex2[ ] )
{
int tmpC[ASIZE]; //ASIZE = 50
int tmpE[ASIZE];
int i, j, k, b, x = 0;
init_polynom(tmpC, tmpE); //sets all values within tmpC and tmpE to 0
for(i=0;i<ASIZE;i++)
{
for(j=0;j<ASIZE;j++)
{
if(ex1[i] > ex2[j])
{
tmpC[x] = co1[i];
tmpE[x] = ex1[i];
x++;
}
else if(ex1[i] == ex2[j])
{
if((ex1[i] == 0) && (ex2[j] == 0))
{
if(k == 0)
{
tmpC[x] = co1[i] + co2[j];
tmpE[x] = 0;
x++;
k = 1;
}
else
{
goto jump;
}
}
else
{
tmpC[x] = co1[i] + co2[j];
tmpE[x] = ex1[i];
x++;
}
}
else if(ex1[i] < ex2[j])
{
tmpC[x] = co2[j];
tmpE[x] = ex2[j];
x++;
}
}
}
jump:
for(b=0;b<ASIZE;b++)
{
co1[b] = tmpC[b];
ex1[b] = tmpE[b];
}
}
try to give k a value before entering the loop
In your inner loop you're incrementing x beyond ASIZE yet you use it to index into arrays you created with a length of ASIZE.

How to use OCIBindDynamic to INPUT/OUTPUT in one variable?

I have some code on OCI/C transport for my program. But I haven't any result after using struct with OCIBindDynamics, I think error where I need to remove cbf_no_data, and add BindByName for output variable after bind by dynamic. I use not a stack for memory, so problem not in data removing, after function
int conn_dynamic(uint16_t id,int pos,char *name,uint16_t type,uint32_t size,int16_t ind,void *data,uint16_t typein,uint32_t sizein,int16_t indin,void *datain,uint16_t mass_arr){
CHECK_CURSOR_ID(id)
int state = 1;
cb_context_t* cbct = (cb_context_t*)malloc(sizeof(cb_context_t));
cbct->cht.ptr = (void*)malloc(sizeof(void*));
cbct->err = connection.errhp;
temp_arr_num = mass_arr;
CHECK_IN_ID(id, pos)
uint8_t bindbyname = 1;
char bindname[65536];
uint32_t bindpos;
if (name[0] >= '0' && name[0] <= '9') {
bindbyname = 0;
bindpos = atoi(name);
} else {
bindname[0] = ':';
strcpy(bindname + 1, name);
}
connection.statements[id].inbinds[pos].type = typein;
connection.statements[id].inbinds[pos].ind = indin;
memcpy(connection.statements[id].inbinds[pos].ptr, datain, sizein);
if (typein == SQLT_CLOB || typein == SQLT_BLOB) {
assert(connection.statements[id].inbinds[pos].lob == NULL);
OCI_CALL(OCIDescriptorAlloc(connection.envhp, (void **)&connection.statements[id].inbinds[pos].lob, OCI_DTYPE_LOB, 0, 0));
OCI_CALL(OCILobCreateTemporary(connection.svchp, connection.errhp, connection.statements[id].inbinds[pos].lob, (ub2)OCI_DEFAULT, OCI_DEFAULT,
(typein == SQLT_CLOB)?OCI_TEMP_CLOB:OCI_TEMP_BLOB, OCI_ATTR_NOCACHE, OCI_DURATION_SESSION));
OCI_CALL(OCILobOpen(connection.svchp, connection.errhp, connection.statements[id].inbinds[pos].lob, OCI_LOB_READWRITE));
uint32_t amtp = sizein;
OCI_CALL(OCILobWrite(connection.svchp, connection.errhp, connection.statements[id].inbinds[pos].lob, &amtp, 1, datain, sizein, OCI_ONE_PIECE, 0, 0, 0, SQLCS_IMPLICIT));
if (bindbyname) {
OCI_CALL(OCIBindByName(connection.statements[id].handle, &(connection.statements[id].inbinds[pos].handle), connection.errhp, (OraText *) name, strlen(name),
&(connection.statements[id].inbinds[pos].lob), 0, typein, 0, 0, 0, 0, 0, OCI_DATA_AT_EXEC));
} else {
OCI_CALL(OCIBindByPos(connection.statements[id].handle, &(connection.statements[id].inbinds[pos].handle), connection.errhp, bindpos,
&(connection.statements[id].inbinds[pos].lob), 0, typein, 0, 0, 0, 0, 0, OCI_DATA_AT_EXEC));
}
} else {
if (!(connection.statements[id].inbinds[pos].ptr = malloc(sizein))) { //create temporary storage for value
connection.error.code = 301;
strcpy(connection.error.msg, "Out of memory");
return -1;
}
// if (bindbyname) {
// OCI_CALL(OCIBindByName(connection.statements[id].handle, &(connection.statements[id].inbinds[pos].handle), connection.errhp, (OraText *) name, strlen(name),
// &(connection.statements[id].inbinds[pos].ptr), sizein, typein, &connection.statements[id].inbinds[pos].ind, 0, 0, 0, 0, OCI_DATA_AT_EXEC));
// } else {
// OCI_CALL(OCIBindByPos(connection.statements[id].handle, &(connection.statements[id].inbinds[pos].handle), connection.errhp, bindpos,
// &(connection.statements[id].inbinds[pos].ptr), sizein, typein, &connection.statements[id].inbinds[pos].ind, 0, 0, 0, 0, OCI_DATA_AT_EXEC));
// }
}
uint16_t oratype=0;
WRITELOG(params,LDEBUG1,"TYPE IN BIND %d \n", type);
switch (type) {
case 2:{
oratype = SQLT_INT;
OCIBindDynamic(connection.statements[id].outbinds[pos].handle,connection.errhp,(dvoid*)cbct,cbf_no_data,(dvoid*)cbct,cbf_get_numeric_data);
break;
}
case 3:{
oratype = SQLT_FLT;
OCIBindDynamic(connection.statements[id].outbinds[pos].handle,connection.errhp,(dvoid*)cbct,cbf_no_data,(dvoid*)cbct,cbf_get_numeric_data);
break;
}
case 1:
case 4:
case 5:
{
if (type == 1){
oratype = SQLT_STR;
WRITELOG(params,LDEBUG1,"call str\n");
OCI_CALL(OCIBindDynamic(connection.statements[id].outbinds[pos].handle,connection.errhp,(dvoid*)cbct,cbf_no_data,(dvoid*)cbct,cbf_get_string));
}
if (type == 5){ oratype = SQLT_CLOB;
OCIBindDynamic(connection.statements[id].outbinds[pos].handle,connection.errhp,(dvoid*)cbct,cbf_no_data,(dvoid*)cbct,cbf_get_clob_data);
}
if (type == 4){
oratype = SQLT_BLOB;
OCIBindDynamic(connection.statements[id].outbinds[pos].handle,connection.errhp,(dvoid*)cbct,cbf_no_data,(dvoid*)cbct,cbf_get_blob_data);
break;}
case 6:{
oratype = SQLT_RSET;
OCIBindDynamic(connection.statements[id].outbinds[pos].handle,connection.errhp,(dvoid*)cbct,cbf_no_data,(dvoid*)cbct,cbf_ref_cursor);
break;}
}
default:
return -1;
}
printf("error here??");
out_array[temp_arr_num]->type = oratype;
out_array[temp_arr_num]->pos = pos;
printf("No");
//it's not a magic numbers. See outputbind in commands.c
cursorid = id;
//WRITE LOG HERE
return 1;
}
So I don't have output bind, and program try to fetch variable. As example cbf_get_string
sb4 cbf_get_string(dvoid *ctxp, OCIBind *bindp, ub4 iter, ub4 index,
dvoid **bufpp, ub4 **alenp, ub1 *piecep,
dvoid **indpp, ub2 **rcodepp) {
cb_context_t* cbct = (cb_context_t*)ctxp;
ub4 pos = *((ub4 *)ctxp);
/* find out how many rows we are expecting */
if (index == 0) {
int rows = 0;
OCIAttrGet((dvoid*)bindp, OCI_HTYPE_BIND, (dvoid*)&rows, (ub4*)sizeof(int), OCI_ATTR_ROWS_RETURNED, cbct->err);
int sz = rows * sizeof(out_string_t);
void* rs = (void*)malloc(sz);
memcpy(cbct->cht.ptr, &rs, sizeof(void*)); /* ptr is now a pointer to a pointer */
#ifdef DEBUG
char dbuf[256]; snprintf(dbuf, 255, "cbf_get_string: rows=%d rs=%p cbct->cht.ptr=%p bytes=%d", rows, rs, *(void**)cbct->cht.ptr, sz); debug(dbuf);
#endif
}
out_string_t* offset = (out_string_t*) ((*(void**)cbct->cht.ptr) + (index * sizeof(out_string_t)));
*indpp = (dvoid*)&offset->indicator;
*rcodepp = (dvoid*)&offset->rc;
*bufpp = (dvoid*)&offset->bufpp;
int size = sizeof(bufpp);
offset->alenp = size;
*alenp = (dvoid*)&offset->alenp;
*piecep = OCI_ONE_PIECE;
out_array[temp_arr_num]->ptr = cbct->cht.ptr;
out_array[temp_arr_num]->index = index;
WRITELOG(params,LDEBUG1,"string in bind %s \n", *(offset->bufpp));
return OCI_CONTINUE;
}
Can you show me, where I wrong? Cause I can't show some errors. I try only bind 'a' to input and 'a' to output. As example "Begin :a := :b End;
And I need view a

Hamiltonian Cycle with fork

hellow friends
i want to write Hamiltonian Cycle for 5 vertexes with fork. and i want to create a process for each vertex to check is it true vertex in (hamCycleUtil function )or no. so i write this code but it has false output.i cant solve the problem .pleas help.how can i write this code true ?i just want create 5 process to check the vertexes.
/*
* C Program to Find Hamiltonian Cycle
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include<sys/types.h>
#include<unistd.h>
#define V 5
void printSolution(int path[]);
/*
* check if the vertex v can be added at index 'pos' in the Hamiltonian Cycle
*/
bool isSafe(int v, bool graph[V][V], int path[], int pos)
{
if (graph [path[pos-1]][v] == 0)
return false;
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;
return true;
}
/* solve hamiltonian cycle problem */
bool hamCycleUtil(bool graph[V][V], int path[], int pos)
{
int pid;
int s=-1;//counter
if (pos == V)
{
if (graph[ path[pos-1] ][ path[0] ] == 1)
return true;
else
return false;
}
for (int v = 1; v < V; v++)
{
pid=fork();
s++;
if(s<V)// to control the number of fork
{
if(v==1)
{
pid=1;}
pid=fork();
s++;
if(pid < 0) {
printf("Error");
}
else if (pid == 0){
if (isSafe(v, graph, path, pos))
{
path[pos] = v;
if (hamCycleUtil (graph, path, pos+1) == true)
return true;
path[pos] = -1;
}
}
else {
if (isSafe(v, graph, path, pos))
{
path[pos] = v;
if (hamCycleUtil (graph, path, pos+1) == true)
return true;
path[pos] = -1;
}
}
}
}
return false;
}
/* solves the Hamiltonian Cycle problem using Backtracking.*/
bool hamCycle(bool graph[V][V])
{
int *path = malloc(V*sizeof(int));
for (int i = 0; i < V; i++)
path[i] = -1;
path[0] = 0;
if (hamCycleUtil(graph, path, 1) == false)
{
printf("\nSolution does not exist");
return false;
}
printSolution(path);
return true;
}
/* Main */
void printSolution(int path[])
{
printf("Solution Exists:");
printf(" Following is one Hamiltonian Cycle \n");
for (int i = 0; i < V; i++)
printf(" %d",path[i]);
printf(" %d",path[0]);
}
int main()
{
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) */
bool graph1[V][V] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0},
};
{ hamCycle(graph1);
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3) (4) */
bool graph2[V][V] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
};
hamCycle(graph2);
return 0;
}}

Wave Algorithm (Lee's Algorithm): incorrect final matrix

I'm writing a program calculating the shortest way from point A to point B.
I have a map (matrix) with values:
0 is block (wall, no way to pass);
1 is free way (you can pass);
2 is start point;
In the code below I declare 2 arrays: an array " map"and changed array "visited" while running program demonstrating visited points.
I check the cells in 4 directions (not diagonals) for 1 or 0. If it's 1 (possible to pass), I increase the counter for 1. For do not count the previous cell I'm trying to avoid it by the condition. I realized that in two one-dimensional arrays {1 0 -1 0} and { 0, 1, 0, -1 } to check neighbor points (what mean i check [i+1][j], [i-1][j], [i][j+1] and [i][j-1]).
As a result I wanna see "visited" matrix with a few lines which shows the way to reach to the point B (1, 2, 3, ... 15). I wanna find the way to map[7][7] point.
Right now the error here that I do count++ for the previous position. How to avoid that?
Thank you.
P.S. I wrote a few functions implementing a new array with 0 values, counting free to go cells and printing arrays.
main.c:
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#define WIDTH 8
#define HEIGHT 8
int mapZero(int map[WIDTH][HEIGHT]);
int mapPrint(int map[WIDTH][HEIGHT]);
int mapInit(int map[WIDTH][WIDTH]);
int findFreeToGoCells(int map[WIDTH][HEIGHT]);
int main(int argc, char * argv[])
{
bool stop;
unsigned int count;
unsigned int max;
int visited[WIDTH][HEIGHT];
int map[WIDTH][HEIGHT] =
{
{ 1, 1, 1, 1, 1, 0, 0, 1 },
{ 0, 1, 1, 1, 1, 1, 0, 1 },
{ 0, 0, 1, 0, 1, 1, 1, 0 },
{ 1, 0, 1, 1, 1, 0, 1, 1 },
{ 0, 0, 0, 1, 0, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 0, 0, 1 },
{ 0, 0, 0, 0, 1, 0, 0, 1 },
{ 0, 1, 1, 1, 1, 1, 1, 1 },
};
mapZero(visited);
printf("Matrix of zeroed-visited cells:\n\n");
mapPrint(visited);
printf("Matrix of the map:\n\n");
mapPrint(map);
printf("Free to go cells: %d\n\n", findFreeToGoCells(map));
max = WIDTH * HEIGHT - 1;
visited[0][0] = map[0][0];
count = 0;
visited[0][0] = 0;
int di[4] = { 1, -1, 0, 0 };
int dj[4] = { 0, 0, 1, -1 };
//do
{
for (int i = 0; i < WIDTH; ++i)
{
for (int j = 0; j < HEIGHT; ++j)
{
if (visited[i][j] == count)
{
for (int k = 0; k < 4; ++k)
{
int i_check = i + di[k];
int j_check = j + dj[k];
if ((i_check >= 0 && i_check < WIDTH) && (j_check >= 0 && j_check < HEIGHT) && (map[i_check][j_check] != 0))
{
visited[i_check][j_check] = count + 1;
}
}
count++;
}
}
}
}// while (visited[7][7] == 0);
if (count > max + 99999)
printf("The way couldn't be found\n");
else
{
printf("Matrix of visited cells:\n\n");
mapPrint(visited);
printf("Free to go cells from [0][0] to [7][7]: %d\n", findFreeToGoCells(visited));
}
/*************************************************************************************/
/*************************************************************************************/
int len;
int x = 7;
int y = 7;
int x_path[WIDTH * HEIGHT];
int y_path[WIDTH * HEIGHT];
len = visited[7][7];
count = len;
while (count > 0)
{
x_path[count] = x;
y_path[count] = y;
count--;
for (int k = 0; k < 4; ++k)
{
int i_check = x + di[k];
int j_check = y + dj[k];
if ((i_check >= 0 && i_check < WIDTH) && (j_check >= 0 && j_check < HEIGHT) && (map[i_check][j_check] == count))
{
x = x + di[k];
y = y + dj[k];
break;
}
}
}
x_path[0] = 0;
y_path[0] = 0;
printf("\nThe shortest way consist of %d cells\nThere are %d the shortest way to reach th the final point\n\n", len, findFreeToGoCells(visited)-len);
system("pause");
return 0;
}
int mapZero(int map[WIDTH][HEIGHT])
{
for (int i = 0; i < WIDTH; ++i)
{
for (int j = 0; j < HEIGHT; ++j)
{
map[i][j] = 0;
}
}
return 0;
}
int mapPrint(int map[WIDTH][HEIGHT])
{
for (int i = 0; i < WIDTH; ++i)
{
for (int j = 0; j < HEIGHT; ++j)
{
printf("%2d ", map[i][j]);
}
printf("\n\n");
}
printf("\n");
return 0;
}
int findFreeToGoCells(int map[WIDTH][HEIGHT])
{
int count = 0;
for (int i = 0; i < WIDTH; ++i)
{
for (int j = 0; j < HEIGHT; ++j)
{
if (map[i][j] != 0) count++;
}
}
return count;
}
Result:

Resources