#include "xdrfile/xdrfile_xtc.h"
#include "xdrfile/xdrfile.h"
#include<stdio.h>
int main()
{
int nat;
int step;
float time;
float prec;
int status;
matrix box;
rvec k[3];
XDRFILE* xfp=xdrfile_open("test2.xtc","r");
status=read_xtc(xfp,nat,&step,&time,box,k,&prec);
xdrfile_close(xfp);
return 0;
}
I tried to run the code using the xtc library to read a trajectory frame of GROMACS... I am getting an error,
Segmentation error
Can you please help???
Looking at this code
Second parameter nat must be set to a value retrieved read_xtc_natoms function. The value must be initialized anyway.
Moreover the array k width must match the nat value.
#include "xdrfile/xdrfile_xtc.h"
#include "xdrfile/xdrfile.h"
#include<stdio.h>
int main(void)
{
int nat;
int step;
float time;
float prec;
int status;
matrix box;
int status;
char fileName[] = "test2.xtc";
status = read_xtc_natoms(fileName, &nat);
if (status != exdrOK)
{
XDRFILE* xfp = xdrfile_open(fileName, "r");
if (xfp != NULL)
{
rvec k[nat];
status = read_xtc(xfp, nat, &step, &time, box, k, &prec);
xdrfile_close(xfp);
}
else
{
perror("File not opened:");
}
}
else
{
fprintf(stderr, "read_xtc_natoms failure; return code %d", status);
}
return 0;
}
In the above code I used VLAs to create the k array, but you can use dynamic memory too:
#include "xdrfile/xdrfile_xtc.h"
#include "xdrfile/xdrfile.h"
#include<stdio.h>
int main(void)
{
int nat;
int step;
float time;
float prec;
int status;
matrix box;
int status;
char fileName[] = "test2.xtc";
status = read_xtc_natoms(fileName, &nat);
if (status != exdrOK)
{
rvec *k = malloc(nat * sizeof(rvec));
if (k != NULL)
{
XDRFILE* xfp = xdrfile_open(fileName, "r");
if (xfp != NULL)
{
status = read_xtc(xfp, nat, &step, &time, box, k, &prec);
xdrfile_close(xfp);
}
else
{
perror("File not opened:");
}
free(k);
}
else
{
fprintf(stderr, "Error in dynamic allocation of k vector\n");
}
}
else
{
fprintf(stderr, "read_xtc_natoms failure; return code %d", status);
}
return 0;
}
Related
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
How Can I debug a C program on Linux?
(4 answers)
Closed 1 year ago.
I have to build a program which takes in the vertices and edges from a csv file and uses an adjacency matrix to store the distance from one vertex to another and calls the function shortest_path which uses the dijkstra's algorithm to find the shortest path and calls the printpath function to print the information of all the vertices it goes through to get from the origin to the end.The information about the vertices is stored in the array of structures arr[].
The problem is that the program stops working when main() call the shortest_path() and the return value is 3221225725
The shortest_path function runs on its own in another program I made but is not called in the main when I execute this program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUFFER 100
#define MAX_NB 8000
#define INFINITY 9999
typedef struct edges edges;
struct edges{
int from,to,weight;
};
typedef struct stops stops;
struct stops {
int id;
float lat,lont;
char title[MAX_BUFFER];
};
stops* arr[MAX_NB]={0};
typedef struct Graph{
int vertices;
// int visited;
} Graph;
int visited[MAX_NB];
int amatrix[MAX_NB][MAX_NB];
int n;
Graph* create_graph(int num_nodes){
Graph* g = (Graph *)malloc(sizeof(struct Graph));
g->vertices=num_nodes;
int i,j;
for(i=0;i<num_nodes;i++){
for(j=0;j<num_nodes;j++){
amatrix[i][j]=0;
}
}
n=num_nodes;
return g;
}
Graph *graph;
int next_field( FILE *f, char *buf, int max ) {
int i=0, end=0, quoted=0;
for(;;) {
// fetch the next character from file
buf[i] = fgetc(f);
// if we encounter quotes then flip our state and immediately fetch next char
if(buf[i]=='"') { quoted=!quoted; buf[i] = fgetc(f); }
// end of field on comma if we're not inside quotes
if(buf[i]==',' && !quoted) { break; }
// end record on newline or end of file
if(feof(f) || buf[i]=='\n') { end=1; break; }
// truncate fields that would overflow the buffer
if( i<max-1 ) { ++i; }
}
buf[i] = 0; // null terminate the string
return end; // flag stating whether or not this is end of the line
}
void fetch_stops ( FILE *csv, struct stops *p) {
char buf[MAX_BUFFER];
next_field( csv, buf, MAX_BUFFER );
p->id = atoi(buf);
next_field( csv, p->title, MAX_BUFFER );
next_field( csv, buf, MAX_BUFFER );
p->lat = atof(buf);
next_field( csv, buf, MAX_BUFFER );
p->lont = atof(buf);
}
void fetch_edges ( FILE *csv, struct edges *p) {
char buf[MAX_BUFFER];
next_field( csv, buf, MAX_BUFFER );
p->from = atoi(buf);
next_field( csv, buf, MAX_BUFFER );
p->to = atoi(buf);
next_field( csv, buf, MAX_BUFFER );
p->weight = atoi(buf);
}
void print_stops( struct stops *p ) {
printf("%d \t \t %s \t %f %f\n",
p->id,p->title, p->lat, p->lont);
}/*
void print_edges( struct edges *p ) {
printf("%d \t \t %d \t %d\n",
p->from,p->to, p->weight);
}
*/
int load_vertices(char *fname){
FILE *f;
struct stops pArray[MAX_NB];
struct stops p;
f=fopen(fname,"r");
if(!f) {
printf("unable to open file\n");
return 0;
}
fetch_stops( f, &p ); // discard the header data in the first line
int ngames = 0;
while(!feof(f)) {
fetch_stops( f, &pArray[ngames]);
arr[ngames]=&pArray[ngames];
ngames++;
}
printf("loaded %d vertices\n",ngames);
fclose(f);
graph = create_graph(ngames);
return 1;
}
void add_edge(int from, int to, int weight){
amatrix[from][to]=weight;
amatrix[to][from]=weight;
}
int load_edges(char *fname/*,Graph *g*/){
FILE *f;
struct edges pArray[MAX_NB];
struct edges p;
f=fopen(fname,"r");
if(!f) {
printf("unable to open file\n");
return 0;
}
fetch_edges( f, &p ); // discard the header data in the first line
int nedges = 0;
int from,to,weight;
while(!feof(f)) {
fetch_edges( f, &pArray[nedges]);
nedges++;
}
int i;
for(i=0;i<nedges;i++){
add_edge(pArray[i].from,pArray[i].to,pArray[i].weight);
}
printf("loaded %d edges\n",nedges);
fclose(f);
return 1;
}
void printpath(int parent[], int u){
// Base Case : If j is source
if (parent[u] == - 1)
return;
printpath(parent, parent[u]);
printf("%d %s\n", arr[u]->id, arr[u]->title);
}
void shortest_path(int origin, int end){
printf("Works1");
int distance[MAX_NB];
int pred[MAX_NB];
int cost[MAX_NB][MAX_NB];
int count,minD,nextn,i,j;
pred[0]=-1;
int n=MAX_NB;
printf("Works2");
for (i = 0; i < n; i++){
for (j = 0; j < n; j++){
if (amatrix[i][j] == 0)
cost[i][j] = INFINITY;
else
cost[i][j] = amatrix[i][j];
}
}
for (i = 0; i <n; i++) {
distance[i] = cost[origin][i];
}
printf("Works1");
distance[origin] = 0;
printf("Works2");
visited[origin] = 1;
count = 1;
while (count < n - 1) {
minD = INFINITY;
for (i = 0; i < n; i++){
if ((distance[i] < minD) && (visited[i])!=1) {
minD = distance[i];
nextn = i;
}}
visited[nextn] = 1;
for (i = 0; i < n; i++)
if (!(visited[i]))
if (minD + cost[nextn][i] < distance[i]) {
distance[i] = minD + cost[nextn][i];
pred[i]=nextn;
}
count++;
}
printf("Works");
printpath(pred,end);
}
int main () {
load_vertices("vertices.csv");
load_edges("edges.csv")
printf("%d",amatrix[300][7490]);
shortest_path(300,253);
return EXIT_SUCCESS;
}
If I run my code when the const N is higher than a specific value (like 30,000 or more), I get "Process terminated with status -1073741510" and the values in my result.dat are not what it supposed to be.
I've tried to look up possible solutions, I know it's a stack overflow problem, but I can't find out anything about what should I modify in my code in order to work.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#define N 5000
//static int nep[N];
int main()
{
srand(time(NULL));
int nap=365, szam=0,ember;
float beta=0.3,gamma=0.7,delta=0.05,valseg;
int dbErzekeny,dbBeteg,dbGyogyult;
int *nep;
nep = (int*) malloc(N * sizeof(int));
if(nep == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
//nep = malloc(N * sizeof(char));
int i,j;
FILE *fp;
fp = fopen("eredmeny.dat", "w");
dbErzekeny=N-1;dbBeteg=1;dbGyogyult=0;
nep[0]=1;
for(i=1;i<N;i++){
nep[i]=0;
}
for(i=1; i<=nap; i++){
for(j=0;j<N;j++){
szam=(rand()%N);
if(nep[szam]==0){
ember=(rand() % N);
if(nep[ember]==1){
valseg=(rand() % 100);
valseg=valseg/100;
if(valseg <=gamma){
nep[szam]=1;
dbErzekeny=dbErzekeny-1;dbBeteg=dbBeteg+1;
}
}
}
if(nep[szam]==1){
valseg=(rand() % 100);
valseg = valseg/100;
if(valseg<= beta){
nep[szam]=2;
dbBeteg=dbBeteg-1;dbGyogyult=dbGyogyult+1;
}
}
if(nep[szam]==2){
valseg=(rand() % 100);
valseg = valseg/100;
if(valseg <= delta){
nep[szam]=1;
dbBeteg=dbBeteg+1;dbGyogyult=dbGyogyult-1;
}
}
}
if(fp!=NULL){
fprintf(fp,"%d; %d; %d; %d; \n",i,dbErzekeny,dbBeteg,dbGyogyult);
}else{
printf("Error!");
}
}
free(nep);
fclose(fp);
return 0;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have to speed up searching of a MAC address in an array (size: 32k). I would like to get better performance out of it, I wrote a little example code to show the problem (mind that the MACs in the array are going to be random numbers (random ports, random vlans) and not nicely ordered (as displayed in the example code).
Now I'm looking for suggestions how I can improve that i.e. speed it up:
#include <stdio.h>
#include <string.h>
#define MAX_MAC 32768
typedef unsigned char l2_mac_t[6];
typedef struct l2_s {
int prt;
int vln;
l2_mac_t mac;
}l2_t;
int find_mac(int port, int vlan, l2_mac_t mac);
void fill_mac(void);
static l2_t arr[MAX_MAC] = {0};
int main (void) {
int i = 0;
int res = 0;
fill_mac();
for (i=0;i<MAX_MAC;i++) {
res = find_mac(arr[i].prt,arr[i].vln,arr[i].mac);
if (res%1000 == 0 )
printf("Got MAC %d\n",res);
}
}
int find_mac(int port, int vlan, l2_mac_t mac) {
int i = 0;
for (int i = 0;i< MAX_MAC; i++) {
if (arr[i].prt == port) {
if (arr[i].vln == vlan) {
if (memcmp(arr[i].mac,mac,sizeof(l2_mac_t)) == 0 ) {
//found
return i;
}
}
}
}
}
void fill_mac(void) {
int i = 0;
for (i=0;i<MAX_MAC; i++) {
arr[i].prt = 4;
arr[i].vln = 10;
arr[i].mac[5] = i%255;
arr[i].mac[4] = i%65025;
}
}
Below is some edited code after getting some comments:
Okay,
I was going to use a hash and came up with the below (which gives me a segfault as it doesn't want to allocate this much memory in init()). Plus, this feels kind of like using a sledge hammer at it, there must be a better way to hash this than than the below MacSum(), any suggestions are welcome!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_MAC 32768
#define MacSum(x) (x)[0]*(2^24) \
+(x)[1]*(2^20) \
+(x)[2]*(2^16) \
+(x)[3]*(2^12)\
+(x)[4]*(2^8)\
+(x)[5]
typedef unsigned char l2_mac_t[6];
typedef struct l2_s {
int prt;
int vln;
l2_mac_t mac;
}l2_t;
static unsigned short *L2Hash=0;
int find_mac(int port, int vlan, l2_mac_t mac);
void fill_mac(void);
void init(void);
static l2_t arr[MAX_MAC] = {0};
int main (void) {
int i = 0;
int res = 0;
init();
fill_mac();
for (i=0;i<MAX_MAC;i++) {
res = find_mac(arr[i].prt,arr[i].vln,arr[i].mac);
/*if (res%1000 == 0 )
printf("Got MAC %d\n",res);*/
}
}
int find_mac(int port, int vlan, l2_mac_t mac) {
int i = 0;
int key = 0;
key = MacSum(mac);
if (memcmp(arr[key].mac,mac,sizeof(l2_mac_t)) == 0 ) {
return key;
} else {
for (int i = 0;i< MAX_MAC; i++) {
if (arr[i].prt == port) {
if (arr[i].vln == vlan) {
if (memcmp(arr[i].mac,mac,sizeof(l2_mac_t)) == 0 ) {
return i;
}
}
}
}
}
}
void fill_mac(void) {
int i = 0;
int key = 0;
for (i=0;i<MAX_MAC; i++) {
arr[i].prt = 4;
arr[i].vln = 10;
arr[i].mac[5] = i%255;
arr[i].mac[4] = i%65025;
key = MacSum(arr[i].mac);
L2Hash[key] = i;
}
}
void init(void) {
static int init = 0;
if (init)
return;
L2Hash = (unsigned short*) malloc(0xffffffffffff*sizeof(unsigned short));
}
For a further update to the question, scroll down to the second answer
stylistic note: nested if()s are hard to read. Some people prefer:
int find_mac(int port, int vlan, l2_mac_t mac) {
int i = 0;
for (int i = 0;i< MAX_MAC; i++) {
if (arr[i].prt != port) continue;
if (arr[i].vln != vlan) continue;
if (memcmp(arr[i].mac,mac,sizeof(l2_mac_t)) continue;
//found
return i;
}
return WHAT; //!!11!!1
}
[this should be a comment, but I needed the formatting.]
I followd some of the above suggestions and came up with the below code. I've now reduced the number of MACs to 1000 but I already get some:Could not find MAC messages.
Anybody able to assist me here?
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_MAC 1000
#define SHORT_INIT 0xFFFF
#define MacSum(x) (x)[0]*(2^24) \
+(x)[1]*(2^20) \
+(x)[2]*(2^16) \
+(x)[3]*(2^12)\
+(x)[4]*(2^8)\
+(x)[5]
typedef unsigned char l2_mac_t[6];
typedef struct l2_s {
int prt;
int vln;
l2_mac_t mac;
}l2_t;
static unsigned short l2hash[MAX_MAC]={0};
int find_mac(int port, int vlan, l2_mac_t mac);
void fill_mac_tab(void);
void init(void);
void mac_hash_add (int idx, l2_mac_t mac);
static l2_t arr[MAX_MAC] = {0};
//---------------------------------------------------------------------
int main (void) {
int i = 0;
int res = 0;
init();
fill_mac_tab();
for (i=0;i<MAX_MAC;i++) {
res = find_mac(arr[i].prt,arr[i].vln,arr[i].mac);
}
}
//---------------------------------------------------------------------
void init(void) {
int i = 0;
for (i=0;i<MAX_MAC;i++)
l2hash[i] = SHORT_INIT;
}
//---------------------------------------------------------------------
int find_mac(int port, int vlan, l2_mac_t mac) {
int i = 0;
int k = 0;
k = (MacSum(mac))%MAX_MAC;
if (memcmp(arr[k].mac,mac,sizeof(l2_mac_t)) == 0 ) {
printf("Found MAC %02X:%02X:%02X:%02X:%02X:%02X at key %d\n",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5],k);
return k;
} else {
for (int i = k;i< MAX_MAC; i++ ) {
if (arr[i].prt != port ) continue;
if (arr[i].vln != vlan ) continue;
if (memcmp( arr[i].mac,mac,sizeof(l2_mac_t) )) continue;
printf("Found MAC %02X:%02X:%02X:%02X:%02X:%02X\n",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
return i;
}
}
printf("Could not find MAC %02X:%02X:%02X:%02X:%02X:%02X\n",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
return -1;
}
//---------------------------------------------------------------------
void fill_mac_tab(void) {
int i = 0;
int o = 0;
int key = 0;
for (i=0;i<MAX_MAC; i++) {
// fill table
arr[i].prt = 4;
arr[i].vln = 10;
arr[i].mac[5] = i%255;
if (i>255)
arr[i].mac[4] = i%65025;
mac_hash_add(i,arr[i].mac);
}
}
void mac_hash_add (int idx, l2_mac_t mac) {
int i = 0;
int o = 0;
int k = 0;
k = (MacSum(arr[idx].mac))%MAX_MAC;
printf("k %d\n",k);
if(l2hash[k] == SHORT_INIT ) {
l2hash[k] = i;
} else {
printf("k %d already used, find next\n",k);
// find next empty spot in hash
for (o=k; o<MAX_MAC; o++) {
if (l2hash[o] != SHORT_INIT ) continue;
printf("using %d\n",o);
l2hash[o] = i;
return;
}
printf("unable to find empty key within range \n");
}
}
a working solution of the above looks like:
It still takes a significant amount of time but it's much better than linear searching through the complete array for every MAC every time.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_MAC 32768
#define SHORT_INIT 0xFFFF
#define OK 0
#define ERROR -1
#define MacSum(x) (x)[0]*(2^24) \
+(x)[1]*(2^20) \
+(x)[2]*(2^16) \
+(x)[3]*(2^12)\
+(x)[4]*(2^8)\
+(x)[5]
typedef unsigned char l2_mac_t[6];
typedef struct l2_s {
int prt;
int vln;
l2_mac_t mac;
}l2_t;
static unsigned short l2hash[MAX_MAC]={0};
int find_mac(int port, int vlan, l2_mac_t mac);
int fill_mac_tab(void);
void init(void);
int mac_hash_add (int idx, l2_mac_t mac);
static l2_t arr[MAX_MAC] = {0};
//---------------------------------------------------------------------
int main (void) {
int i = 0;
int rv = OK;
init();
printf("insert\n");
rv = fill_mac_tab();
if (rv) {
printf("ERROR: fill_mac_tab() returned %d\n",rv);
exit (rv);
}
printf("find\n");
for (i=0;i<MAX_MAC;i++) {
rv = find_mac(arr[i].prt,arr[i].vln,arr[i].mac);
if (rv <0) {
printf("ERROR: find_mac() returned %d\n",rv);
exit(rv);
}
}
}
//---------------------------------------------------------------------
void init(void) {
int i = 0;
for (i=0;i<MAX_MAC;i++)
l2hash[i] = SHORT_INIT;
}
//---------------------------------------------------------------------
int find_mac(int port, int vlan, l2_mac_t mac) {
int i = 0;
int k = 0;
k = (MacSum(mac))%MAX_MAC;
if (memcmp(arr[k].mac,mac,sizeof(l2_mac_t)) == 0 ) {
//printf("Found MAC %02X:%02X:%02X:%02X:%02X:%02X at key %d\n",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5],k);
return k;
} else {
for (int i = k;i< MAX_MAC; i++ ) {
if (arr[i].prt != port ) continue;
if (arr[i].vln != vlan ) continue;
if (memcmp( arr[i].mac,mac,sizeof(l2_mac_t) )) continue;
//printf("Found MAC %02X:%02X:%02X:%02X:%02X:%02X\n",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
return i;
}
//printf("continue search from bottom\n");
for (int i = 0;i< k; i++ ) {
if (arr[i].prt != port ) continue;
if (arr[i].vln != vlan ) continue;
if (memcmp( arr[i].mac,mac,sizeof(l2_mac_t) )) continue;
//printf("Found MAC %02X:%02X:%02X:%02X:%02X:%02X\n",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
return i;
}
}
printf("Could not find MAC %02X:%02X:%02X:%02X:%02X:%02X\n",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
return ERROR;
}
//---------------------------------------------------------------------
int fill_mac_tab(void) {
int i = 0;
int o = 0;
int key = 0;
int rv = OK;
for (i=0;i<MAX_MAC; i++) {
// fill table
arr[i].prt = 4;
arr[i].vln = 10;
arr[i].mac[5] = i%255;
if (i>255)
arr[i].mac[4] = i%65025;
rv = mac_hash_add(i,arr[i].mac);
}
return rv;
}
int mac_hash_add (int idx, l2_mac_t mac) {
int i = 0;
int o = 0;
int k = 0;
int rv = OK;
k = (MacSum(arr[idx].mac))%MAX_MAC;
//printf("k %d\n",k);
if(l2hash[k] == SHORT_INIT ) {
l2hash[k] = i;
} else {
//printf("k %d already used, find next\n",k);
// find next empty spot in hash
for (o=k; o<MAX_MAC; o++) {
if (l2hash[o] != SHORT_INIT ) continue;
//printf("using %d\n",o);
l2hash[o] = i;
return OK;
}
//printf("Continue search in bottom half\n");
for (o=0; o<k; o++) {
if (l2hash[o] != SHORT_INIT ) continue;
//printf("using %d\n",o);
l2hash[o] = i;
return OK;
}
//printf("unable to find empty key within range \n");
rv = ERROR;
}
return rv;
}
I am trying to implement a Boyer Moore Horsepoole algorithm. This code was written in Turbo C++, Windows. It worked. I have to port this in ubuntu.
typedef struct skip_table
{
char index;
int value;
}skip_table;
void create_table(char*,int);
int discrete_char(char*,int);
int bm(char*, char*);
int lookup(char);
int check_EOF(char*,int);
skip_table *t1;
int tab_len;
FILE *fptr;
int main()
{
time_t first, second;
double time_spent;
long int cnt=0;
char *key_string,*buf,c; // String to be matched and text
int i,key_len,text_len,def_shift_len,flag_match=0;
gets(key_string);
key_len=strlen(key_string);
fptr=fopen("test_file.txt","r");
first = clock();
fseek(fptr,SEEK_SET,0);
create_table(key_string,key_len);
while(flag_match!=1)
{
fseek(fptr,100*cnt,0);
fread(buf,100-key_len-1, 1, fptr);
flag_match = bm(buf, key_string);
cnt++;
printf("\n%d",cnt);
}
second =clock();
time_spent=(double)(second-first)/CLOCKS_PER_SEC;
if(flag_match==1)
printf("\n\nMatch Found in %lf seconds",time_spent);
else
printf("\n\nMatch NOT Found in %lf seconds",time_spent);
fclose(fptr);
return 0;
}
int discrete_char(char* key_string,char* temp,int key_len)
{
int i,j,count=1,flag=0;
for(i=1;i<key_len;i++)
{
for(j=0; j<count; j++)
{
flag=0;
if(temp[j] == key_string[i])
{
flag=1;
break;
}
}
if(flag!=1)
{
temp[count++]=key_string[i];
flag=0;
}
}
temp[count]='\0';
return count;
}
void create_table(char* key_string,int key_len)
{
int i,j,k,max_index;
char *temp;
temp[0] = key_string[0];
tab_len=discrete_char(key_string,temp,key_len);
t1=(skip_table*)malloc((tab_len-1)*sizeof(skip_table));
for(i=0;i<tab_len;i++)
{
for(j=0;j<key_len;j++)
{
if(temp[i]==key_string[j])
max_index=j;
}
t1[i].index=temp[i];
t1[i].value=key_len-max_index-1;
printf("\n\n %c %d",t1[i].index,t1[i].value);
}
}
int bm(char* text, char* key_string)
{
int i_t, i_k, j,k, text_len, key_len, shift, count=0, flag_match=0;
int loop_count;
text_len = strlen(text);
key_len = strlen(key_string);
i_t=key_len;
i_k=key_len;
loop_count=0;
while(i_t<=text_len)
{
if(count != key_len)
{
if(text[i_t-1]==key_string[i_k-1])
{
count++;
i_t--; i_k--;
loop_count++;
}
else
{
if(loop_count>key_len)
{
i_t=i_t+lookup(text[i_t-1])+1;
i_k=key_len;
loop_count=0;
continue;
}
shift = lookup(text[i_t-1]);
if(shift<=0)
shift=key_len;
i_t = i_t+shift;
i_k = key_len;
count=0;
}
}
else
{
flag_match = 1;
break;
}
}
return flag_match;
}
"int lookup(char index)" returns the respective value field of the index if present in "temp" else returns -1.
There's my whole code.
Not that I see exactly what went wrong but here are some defensive programming tips:
int main()
{
// initialize all variables before use
time_t first = 0, second = 0;
double time_spent = 0.0;
long int cnt=0;
char *key_string = NULL;
char *buf = NULL;
char c = '\0';
char temp[50] = {0};
int i = 0,key_len=0,text_len=0,def_shift_len=0,flag_match=0;
// use fgets instead of gets, fgets allows you specify max length
fgets(temp,sizeof(temp),stdin);
key_len=strlen(temp);
key_string = (char*) malloc(key_len+1);
// use strncpy or strcpy_s to specify max size
strncpy(key_string, temp, sizeof(key_string));
fptr = fopen("test_file.txt","r");
first = clock();
// here arguments have wrong order, fseek takes origin as last arg:
fseek(fptr,0,SEEK_SET);
// could be something in create_table, but you have not supplied it
create_table(key_string,key_len);
When you have so many variables in a function you may consider moving out parts of the function to other functions
Try using --track-origins=yes on your valgrind options as well, as the output suggests, this can help track down where uninitialised varables have come from.
As others have suggested, the issue valgrind is reporting is inside create_table, so please post the code for that as well.
I am trying to execute the below code, but for every attempt I am geting a segmentation fault. The problem seems to be coming from the strncpy function used in tokenizing. I a bit new to programming. Please help me debug the code. Please help:
/*
** Program to accept a binary IP address from the command line and
** if it is a valid IP address, show the user its dotted decimal form.
** Also tell the user, which class of IP address it belongs to
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
int validchk(char uarg[]);
int tokenize(char uarg[], char* uargv[]);
int toNum(char harr[], char iparr[]);
void shownum(char *iparr[]);
void classify(char uarg[]);
void usage();
void mystrncpy(char* arr, char* brr);
int main(int argc, char *argv[])
{
char* ipStr[9];
if (argc != 2) {
usage();
exit(1);
}
if (validchk(argv[1]) == FALSE) {
fprintf(stderr,"Error in the length of the IP Bit Address\n");
exit(1);
}
classify(argv[1]);
if (tokenize(argv[1],ipStr) == -1) {
perror("Error in tokenizing the binary IP address\n");
}
//shownum(ipStr);
return 0;
}
void usage()
{
fprintf(stderr,"Usage: bi2ip <32bitip>\n");
return;
}
int validchk(char uarg[])
{
if (strlen(uarg) != 32) {
return FALSE;
}
}
void classify(char uarg[])
{
int ipcnt = 0;
char *p;
int doneflag = FALSE;
while(ipcnt <= 4) {
p = &uarg[ipcnt];
if (*p == '0') {
doneflag = TRUE;
break;
}
ipcnt++;
}
if (doneflag == FALSE) {
fprintf(stderr,"Failed to classify\n");
exit(1);
}
printf("%c\n",('A'+ipcnt));
return;
}
int tokenize(char uarg[], char* uargv[])
{
int i =0,j;
// for (i = 0; i <4; i++) {
// strncpy(&uargv[i][0],&uarg[j],8);
//strncpy(uargv[1],&uarg[8],8);
//strncpy(uargv[2],&uarg[16],8);
//strncpy(uargv[3],&uarg[24],8);
// uargv[i][8] = '\0';
// j+=8;
for ( j = 0; j<8; j++) {
uargv[0][j] = uarg[j];
uargv[1][j] = uarg[j+8];
uargv[2][j] = uarg[j+16];
uargv[3][j] = uarg[j+24];
}
// }
return 0;9
}
void shownum(char *iparr[])
{
int i,j;
unsigned long arr[4];
for(i = 0; i<4; i++) {
arr[i] = strtoul(iparr[i],NULL,2);
}
for ( j = 0; j < 3; j++) {
printf("%lu.",arr[j]);
}
printf("%lu",arr[3]);
}
char* ipStr[9];
The above creates an array of 9 strings (pointers to char). It does not, however, allocate memory for the nine strings.
When you strncpy into ipStr, your program segfaults.
Solution: allocate memory (e.g. using malloc() or strdup()).
Your validchk() function fails to return TRUE if the address validates. This will make it behave more or less randomly.
You should rewrite it, keeping the same core validation rule, as:
int validchk(const char *string)
{
return (string != NULL) && (strlen(string) == 32);
}