As the title states, I'm getting an error
Access violation reading location 0xCDCDCDCD.
Now I'm dealing with an array of linked lists, and I believe the trouble to be something around adding to the linked list. I'm fine with this usually, but I feel I'm doing something wrong with memory allocation.
Here are my structs:
Graph:
typedef struct graph
{
int V;
int *state;
EdgeList *edges;
} Graph;
Edge:
typedef struct edge
{
int toVertex;
int weight;
} Edge;
EdgeList:
typedef struct edgeNode
{
Edge edge;
struct edgeNode *next;
} *EdgeList;
Here is the main function that runs it all:
main()
{
Graph myGraph;
scanf("%d", &(myGraph.V));
myGraph.state = (int)malloc(myGraph.V*sizeof(int));
myGraph.edges = (EdgeList*)malloc(myGraph.V*sizeof(EdgeList));
int *inDegrees;
inDegrees = (int)malloc(sizeof(int)*myGraph.V);
/* Sets all array values to 0 */
for (int counter = 0; counter < myGraph.V; counter++)
{
inDegrees[counter] = 0;
}
for (int i = 0; i < myGraph.V; i++)
{
int number_of_edges;
int input = 0; /*For that little experimental bit*/
scanf("%d", &(myGraph.state[i]));
scanf("%d", &number_of_edges);
if (number_of_edges > 0)
{
for (int j = 0; j < number_of_edges; j++)
{
Edge newEdge;
scanf("%d,%d", &(newEdge.toVertex), &(newEdge.weight));
inDegrees[newEdge.toVertex]++;
printf("%s%d\n", "\nOoh, new input for ", newEdge.toVertex);
/*insert at front*/
EdgeList newNode = (EdgeList)malloc(sizeof (struct edgeNode));
newNode->edge = newEdge;
newNode->next = myGraph.edges[i];
myGraph.edges[i] = newNode;
/* Bit to calculate state.*/
EdgeList current = myGraph.edges[i];
while (current != NULL)
{
if (current->edge.toVertex == i)
{
input += (current->edge.weight)*(myGraph.state[i]);
}
current = current->next;
}
}
if (input > 0)
{
myGraph.state[i] = 1;
}
else
{
myGraph.state[i] = 0;
}
}
}
//print
for (int k = 0; k < myGraph.V; k++)
{
printf("\n%s%d%s", "In degrees for ", k, ": ");
printf("%d", inDegrees[k]);
}
}
In particular, the error comes during the traversal of the linked list. It's in the above code, but I'll highlight it here:
EdgeList current = myGraph.edges[i];
while (current != NULL)
{
if (current->edge.toVertex == i)
{
input += (current->edge.weight)*(myGraph.state[i]);
}
current = current->next;
}
If anyone can help, it'd be greatly appreciated because I'm rather stuck.
An value in uninitialized buffer allocated via malloc() is assigned to newNode->edge in newNode->next = myGraph.edges[i];.
The newNode is set to current via myGraph.edges[i] = newNode; and EdgeList current = myGraph.edges[i];.
Assuming that malloc() succeeded, current isn't NULL here, so it is entering the loop.
The uninitialized value assinged in 1 is assigned to current in current = current->next;.
An undefined behavior is invoked by using value in buffer allocated via malloc() and uninitialized at current != NULL.
To fix this error, initialize myGraph.edges in, for example, this way:
myGraph.edges = (EdgeList*)malloc(myGraph.V*sizeof(EdgeList));
for (int i = 0; i < myGraph.V; i++)
{
myGraph.edges[i] = NULL;
}
Also, remove the harmful casts to int of the pointer returned from malloc(). Casting the return values to pointers explicitly is also not considered as good.
Related
Working on implemeting graphs for a CS class project I declared these two structures
typedef struct person {
char name[128];
int age;
} Person;
typedef struct graph {
int knots;
int adjacencies[500][500];
Person personList[500];
} Graph;
void insertPerson(Graph *g, Person p) {
g->personList[knots] = p;
(g->knots)++;
}
void writeAdjacencies(Graph g) {
for(int i = 0; i < MAXDIM; i++) {
for(int j = 0; j < MAXDIM; j++) {
printf("%d ", g.adjacencies[i][j]);
}
printf("\n");
}
}
Everything is fine except that when trying to create a menu function (reading inputs and then deciding whether to add new person or remove existing one, etc...) passing a graph pointer and then using it's pointed instance seems to be generating a segmentation fault.
void checkInput(int input, Graph *g) {
int temp;
char tempName[128];
if(input == 1 ) {
printf("\n Name: ");
scanf(" %[^\n]", tempName);
printf("%s\n", tempName);
Person p;
strcpy(p.name, tempName);
/* takes graph pointer a person and just adds person to personList and increases knots
it's working as intended
*/
insertPerson(g, p);
/* Goes through each element in the matrix and prints it
this is the one causing problems
*/
writeAdjacencies(*g);
}
}
The code is working fine until the moment I pass *gas an argument - that is if I put the writeAdjacencies(*g) under a comment it does not cause any trouble.
I don't get what is the issue here? I feel as if I'm using pointers like I did so far throughout the year and it worked. Maybe I could be passing a null pointer? But I did inialize it in the main function I think.
main.c :
Graph graph;
for(int i = 0; i < MAXDIM; i++) {
for(int j = 0; j < MAXDIM; j++) {
g.adjacencies[i][j] = 0;
}
}
g.knots = 0;
checkInput(0, &g);
Any help is welcomed!
EDIT: included both missing functions
Ignoring the potential buffer overflows from your scanf code, your Graph structure is way too large for the stack (containing 250,000 integers). Use dynamic memory allocation instead. E.g.:
typedef struct {
int** adjacencies;
int n;
} Graph;
void graph_init(Graph* g, int n) {
g->n = n;
g->adjacencies = malloc(n * sizeof(int*));
for (int i = 0; i < n; ++i) {
g->adjacencies[i] = malloc(n * sizeof(int));
}
}
void graph_free(Graph* g) {
for (int i = 0; i < g->n; ++i) {
free(g->adjacencies[i]);
}
free(g->adjacencies);
g->n = 0;
}
I'm trying to figure out how to find the length of the longest prefix of two words in Trie. I was trying to find a solution, but I found nothing.
I already have an implementation of Trie, where the nodes are represent by structure:
struct node
{
int end; // 1 if node is end of word or 0 if not
int count; // The number of words that contain current node
struct node *letter[26]; // Array of nodes, which represent the alphabet
};
int length_of_longest_prefix(struct node *root)
{
//??????????
}
I tried to make a recursive function for this problem, but I could not do it.
Let´s think about this filled trie:
Filled trie
What is the best way to solve this problem?
Pseudocode will be very usefull.
My function:
//Global variable
int total_max;
//root = start
int length_of_longest_prefix(struct node *root, struct node *start)
{
int max = 0;
int depth = 0;
for (int i = 0; i < 26; i++)
{
if(root->letter[i] != NULL && root->letter[i]->count >= 2)
{
depth = length_of_longest_prefix(root->letter[i], start);
depth++;
if(root->letter[i] == start->letter[i])
{
depth = 0;
}
}
if(depth > total_max)
total_max = depth;
}
return depth;
}
int main(void)
{
total_max = 0;
struct node *root = (struct node*)malloc(sizeof(struct node));
for (int i = 0; i < 26; i++)
{
root->letter[i] = NULL;
}
root->end = 0;
root->count = 0;
/*Inserting strings to Trie*/
length_of_longest_prefix(root, root);
printf("%d\n", total_max);
return 0;
}
I was asked to build a function that's receive a static two dimensional array with a lot of zeroes and turn it to an array of structs. each struct contains the value which is not zero and the index of the column.
Now I have built it but the problem is with the print function.
1) When I try to print twice it only prints one time and the second time list becomes NULL. Why does this occur?
print(list);
print(list);
2) Why can't I print like I did in the main function?
printf("this is just a print |%d||%d| ", list[0]->next->next->next->data, list[0]->col);
Why I don't have access to it, the program crashes...
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
//#include <vld.h>
#include <string.h>
#include <ctype.h>
#define C 5
#define N 4
typedef struct Node {
int data;
int col;
struct Node *next;
} node;
node **fun(int arr[N][C]) {
int i, j, k;
node **list;
node *temp;
list = (node**)calloc(N, sizeof(node *));
for (i = 0; i < N; i++) {
list[i] = NULL;
for (j = C - 1; j >= 0; j--)
if (arr[i][j] != 0) {
temp = (node*)malloc(sizeof(node));
temp->data = arr[i][j];
temp->col = j;
temp->next = list[i];
list[i] = temp;
}
}
return list;
}
void print(node **head) {
int i;
node **temp = head;
for (i = 0; i < N; i++) {
while (temp[i]) {
printf("|%d||%d| ", temp[i]->data, temp[i]->col);
temp[i] = temp[i]->next;
}
printf("\n\n");
}
}
void main() {
int arr[N][C] = { {0,0,4,0,7}, {3,0,0,0,0}, {9,1,0,6,0} , {0,0,0,0,0} };
node **list;
list = fun(arr);
print(list); ///////////
print(list); ///////////////
printf("this is just a print |%d||%d| ", list[0]->next->next->next->data, list[0]->col);
}
As was mentioned in the comments, you are destroying your list of pointer in the process of printing them:
while(temp[i])
{ printf("|%d||%d| ",temp[i]->data,temp[i]->col);
temp[i]=temp[i]->next; // <---- here
}
Each temp[i] is the same as head[i], so you modify the original list as you do this. The while loop exits when this value is NULL, so the end result is that all array elements are NULL.
You need to assign this value to a temporary so you can walk the list without changing it:
node *temp2 = temp[i];
while(temp2)
{ printf("|%d||%d| ",temp2->data,temp2->col);
temp2=temp2->next;
}
Your print function modifies the array: it uses the array elements to iterate through the lists, and leaves them with a NULL value.
Here is a corrected version:
void print(node **head) {
int i;
for (i = 0; i < N; i++) {
node *temp;
for (temp = head[i]; temp; temp = temp->next) {
printf("|%d||%d| ", temp->data, temp->col);
}
printf("\n\n");
}
}
i am trying to implement a linked-list in C with the aim to do a BFS on it.
The input for the list should look like this:
a-bc
b-a
c-a
which represents a list looking like this:
a
/ \
b c
now, my problem is that I cannot read the variable name defined in my Vertex struct. My program segfaults with Access Reading Violation. While printf("%s", s) takes a char *, casting the name to a char* doesn't help. The error takes place before the char is even accessed?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Vertex Vertex;
typedef struct Vertex
{
char name;
int visited;
int distance;
Vertex* next;
} Vertex;
struct Vertex* AddVertex(Vertex* head, char newVertexName)
{
Vertex* newHead = malloc(sizeof(Vertex));
newHead->name = newVertexName;
printf("added vertex named: %s", newHead->name); // causing the error
newHead->next = head;
newHead->visited = 0;
newHead->distance = 0;
return newHead;
}
int main()
{
// BFS
char s[100];
int l = 0;
const int nNrOfVerts = 27;
Vertex* adjList[28];
// initialise array of pointers
for(int i = 0; i <= nNrOfVerts; ++i)
{
adjList[i] = NULL;
}
// fill vertices with user data
for(int i = 1; i <= nNrOfVerts; ++i)
{
printf("enter %d vert: ", i);
if(scanf("%s", &s) != 1)
{
break;
}
l = strlen(s);
if(l > 2)
{
for(int k = 0; k < l; ++k)
{
// increment to accustom for the - seperator
if(1 == k)
{
k = 2;
}
adjList[i] = AddVertex(adjList[i], s[k]);
}
}
for(int k = 0; k < 100; ++k)
{
s[k] = NULL;
}
}
bfs(adjList);
// printing the list
for(int i = 1; i <= l; ++i)
{
for(int j = 0; j <= nNrOfVerts; ++j)
{
if(adjList[j]->distance == i)
{
printf("Level: %d is: %s", i, adjList[j]->name);
}
printf("No node for dist: %d", i);
}
}
return 0;
}
How can I access the value of newHead->name or adjList[i]->name for that matter? The interesting thing is, if I try to access adjList[i]->distance the correct integer is returned...
You declared name as a char but then you try to print it as a character :
printf("added vertex named: %s", newHead->name);
Change the %s to %c :
printf("added vertex named: %c", newHead->name);
or change your name to a char *.
I wrote the following code to insert into binary search tree which can have duplicate entries but i get segmentation fault for larger inputs like greater than 30 ....plz help!! The duplicate entries are stored in the right branch of the node
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
typedef struct vertex{
int num;
struct vertex* r;
struct vertex* l;
} node;
void insert(node* T,int x)
{
if(x < T->num)
{
if(T->l == NULL)
{
T->l = (node*)malloc(sizeof(node));
T->l->num = x;
printf("%4d ",x);
return;
}
else
{
insert(T->l,x);
}
}
else if(x >= T->num)
{
if(x == T -> num)
if(T->r == NULL)
{
T->r = (node*)malloc(sizeof(node));
T->r->num = x;
printf("%4d ",x);
return;
}
else
insert(T->r,x);
}
}
main()
{
srand((unsigned int)time(NULL));
int i,n,m,x;
node* T;
printf("n = ");
scanf("%d",&n);
printf("\nm = ",&m);
scanf("%d",&m);
printf("\n\n\n+++ Inserting %d random integers between 1 and %d\n",n,m);
x = 1 + rand() % m;
T = (node*)malloc(sizeof(node));
T->num = x;
printf("%4d (1)",x);
for(i=1;i<n;i++)
{
x = 1+rand() % m;
insert(T,x);
if(i%8 == 7)
printf("\n");
}
printf("\n\n");
}
malloc() does not initialize memory, so set other member to NULL after allocation or use calloc(). Without this you will be accessing random memory when you do T->l or T->r.
T = malloc(sizeof(node));
T->num = x;
T->l = NULL;
T->r = NULL;
or
T = calloc(1, sizeof(node));
T->num = x;
Do this in all places where you use malloc()
malloc(noofbytes) function only allocate noofbytes space only does not initialize with NULL .
This is the problem with your code.
When you allocate memory
T->l = (node*)malloc(sizeof(node));
T->l->num = x;
you allocated memory of size of structure node but it is not initialized . Means
T->l->l and T->l->r is not NULL and have some garbage value.
when you traverse it T->l== NULL or T->r==NULL condition not get satisfied and so it gives segmentation fault.