#define SIZE 7000
static char buf[SIZE];
static char *bufptr = buf;
struct node
{
int reg_num;
int val;
char var_name[30];
char var_str[100];
struct node *memroy;
struct node *next;
};
struct node* add(struct node *head, int i)
{
struct node *temp;
if (head == NULL)
{
temp = (struct node *)malloc(sizeof(struct node));
temp->next = NULL;
temp->reg_num = i;
head = temp;
}
else
{
head->next = add(head->next, i);
}
return head;
}
void* malloc(int n)
{
if (buf + SIZE - bufptr >= n)
{
bufptr += n;
return bufptr - n;
}
else
{
return NULL;
}
}
When I run my programm it crashes during the assignment temp->next = NULL.
I think the problem is in my malloc function. I tested it with malloc in libraries and it worked correctly, but I not allowed to use libraries and must write a new malloc function.
You never check the return of your malloc yet you know it can return NULL;.
Check if temp is NULL before doing temp->next = NULL;
My problem don't has relation with kind of pointer and returned value from malloc().I have problem with size of buf[] and by increment of size my problem solved.Tnx from every one.
Related
I keep getting Segmentation Fault (core dumped) run time error and I can't figure out why.
My code:
struct Node
{
void *next;
void *val;
};
typedef struct Node* NodePtr;
struct List
{
NodePtr head;
};
typedef struct List* ListPtr;
ListPtr create()
{
ListPtr ptr = malloc(sizeof(struct List));
return ptr;
}
int insert(ListPtr list, void *obj)
{
NodePtr newObj = malloc(sizeof(struct Node));
//Cast next as a self referencing Node
newObj->next = (NodePtr) newObj->next;
//Point to beginning of list
NodePtr current = list->head;
if(list->head == NULL)
{
newObj->val = obj;
list->head->next = newObj;
newObj->next = NULL;
return 1;
}
return 0;
}
int main(int argc, char *argv[])
{
int x = 2;
int *p = &x;
ListPtr thing = create();
insert(thing, p);
return 0;
}
The error is here: list->head->next = newObj after some debugging. I thought I had to allocate memory for list->head->next, but when I added the code in for that it still gave me the same error. Am I casting it wrong or not allocating memory correctly? Any help would be appreciated, thanks!
Just put this together, runs fine.
#include <stdlib.h>
#include <stdio.h>
struct Node {
void *next;
void *val;
};
typedef struct Node* NodePtr;
struct List {
NodePtr head;
};
typedef struct List* ListPtr;
ListPtr CreateList() {
ListPtr ptr = malloc(sizeof(struct List));
return ptr;
}
void Insert(ListPtr list, void *obj) {
// create and initialize new node
NodePtr newObj = malloc(sizeof(struct Node));
newObj->val = obj;
newObj->next = NULL;
//Point to beginning of list
NodePtr curr = list->head;
// Add node to the list
if(curr == NULL) // if no head node, make newObj the head node
{
list->head = newObj;
}
else{ // otherwise traverse the list until you find the last node (the one that points to a null as the next)
while(1) {
if(curr->next != NULL) {
curr = curr -> next;
} else {
curr->next = newObj;
}
list->head = newObj;
newObj->val = obj;
list->head->next = newObj;
newObj->next = NULL;
}
}
}
int main() {
int x = 2;
int *p = &x;
ListPtr thing = CreateList();
Insert(thing, p);
return 0;
}
You check if list->head is NULL and then do some operations with that. Change that to if(list->head != NULL)
{
...
}
At a thought, malloc does not guarantee allocated memory is empty. It's good practice to set all values where they matter after allocation.
list->head is probably not null
also : newObj->next = (NodePtr) newObj->next;
doesn't set to a rational value, it sets to whatever memory was set - were you intending newObj->next = (NodePtr) newObj; ?
list->head should not be referenced if null. list->head->next will only be valid if it's not null.
if you actually want to build a list,
newObj->val = obj;
if (list->head == NULL) { newObj->next = list->head; }
list->head = newObj;
either that or travel down list->head->next chain until next is null, and set that to be newObj->next. If that way then it's possibly a good idea, newObj->next should be set to NULL and not itself.
Might want to figure out how your list will behave - is it circular? does it grow from the head (list->head) or tail (last ->next) ? Do you spot the tail when listObject->next == NULL or when listObject->next == listObject ?
I realize that this answer is mostly stylistic. But I do think that (bad) style and (bad) habits are an (important) part of (bad) programming. Summing it up ...
(in most cases) typedefs are not needed; they just introduce an alias for something that already existed.
[rule of seven] human readers have a limited amount of identifiers ("names") that they can keep track of. This could be 7. Minimising the number of distinct words makes reading easier.
also, the reader has to remember that xPtr and xNode are related (typeof *xPtr === typeof xNode)
when reading source code, keywords and special character tokens (such as operators) don't count as an identifier, since you do not have to remember them. (Syntax-highligting helps, too)
if there is only one way of expressing your program, there is no possibility for errors like iPtr *p; p = (qPtr) malloc (sizeof xNode);
creating yet another struct (+typedefs for it), just to accomodate a root pointer will clobber up your mental namespace even more.
Now a rework of the (intended) code:
#include <stdio.h>
#include <stdlib.h>
struct node {
struct node *next;
void *payload;
};
struct node *root=NULL;
void initialize() { /* nothing .... */ }
int insert(struct node **pp, void *pv) {
struct node *p;
p = malloc(sizeof *p);
if (!p) { /* handle error */ return -1; }
p->payload = pv;
p->next = *pp;
*pp = p;
return 1; /* inserted one element */
}
int main(void)
{
int i;
i=666;
/* note: this function call will pass a pointer to a local variable `i`
** to the insert() function, which will remember it.
** This is generally a bad idea, to say the least.
*/
insert( &root, &i);
return 0;
}
I keep getting this Segmentation Fault: 11 error and I don't know why.
My Code:
typedef struct Node* NodePtr;
struct Node
{
NodePtr next;
void *val;
};
struct List
{
NodePtr head;
};
typedef struct List* ListPtr;
int compare(void *one, void *two)
{
if(*(int*)one < *(int*)two)
return -1;
else if(*(int*)one > *(int*)two)
return 1;
return 0;
}
ListPtr create()
{
ListPtr blah = malloc(sizeof(struct List));
memset(blah, 0, sizeof(struct List));
return blah;
}
NodePtr scan(NodePtr head, void *obj)
{
NodePtr previous, current;
previous = head;
current = head->next; // Segmentation fault here!!
while(current != NULL && (compare(curry->val, obj) == -1))
{
previous = current;
current = current->next;
}
return previous;
}
int insert(ListPtr llist, void *obj)
{
NodePtr newobj = malloc(sizeof(struct Node));
NodePtr prevNode, nextNode;
prevNode = search(llist->head, obj);
nextNode = prevNode->next;
if((nextNode == NULL) || (compare(nextNode->val, obj) != 0))
{
prevNode->next = newobj;
newobj->next = nextNode;
return 1;
}
else
{
free(newobj);
}
return 0;
}
I thought head was not allocated, so I added malloc in create for blah->head, but still no luck.
I think the error is here after some debugging: current = head->next.
Any help would be appreciated! Thank you for your time!
EDIT: How I call insert:
int main(int argc, char *argv[])
{
ListPtr list = create();
int x = 2;
int *p = &x;
while(*p != 0)
{
printf("\nEnter a number: ");
scanf("%d", p);
if(*p != 0)
insert(list, p);
}
return 0;
}
You don’t appear to check whether the list is empty when you scan it. However, without a Minimum Complete Verifiable Example that tells us how you called the function, it is impossible to tell for sure what you did.
Update
Now that you have, that seems to be it. You create an empty list and search it inside your insert function. The search function dereferences the zeroed-out pointer in head, causing a segfault.
Try the following: first, check that your pointer is valid in each of your functions before you do anything with it. An empty list should fail every search. Second, for maximum portability, you want to set your head pointer to NULL (since a NULL pointer is not necessarily all-bits-zero on all implementations).
Hey i am starting to work on Huffman coding and I have a bit of a problem I getting this error
Segmentation fault (core dumped)
I understand it is caused by trying to reach memory you are not allow to but I can not realize what is the problem in my code, thank in advnace for the help!
src.txt - http://pastebin.com/kDf8nEhV
#include <stdio.h>
#include <stdlib.h>
int freq[256] = {0};
struct Node {
unsigned char m_ch;
int m_freq;
struct Node* m_ls, *m_rs;
struct Node* m_hls, *m_hrs;
};
struct Node* createNode(int freq, char ch);
void insertTree(struct Node** root, struct Node* n);
struct Node* getBinTree(FILE* fsrc);
void inorder(struct Node* root);
int main() {
FILE* fsrc;
struct Node* tree = (struct Node*)malloc(sizeof(struct Node));
fsrc = fopen("src.txt", "rb");
tree = getBinTree(fsrc);
inorder(tree);
return 1;
}
struct Node* createNode(int freq, char ch) {
struct Node* pNode = (struct Node*)malloc(sizeof(struct Node));
pNode->m_freq = freq;
pNode->m_ch = ch;
return pNode;
}
void insertTree(struct Node** root, struct Node* n) {
if (!(*root)) {
*root = n;
return;
}
if (n->m_freq < (*root)->m_freq) {
insertTree(&(*root)->m_ls, n);
} else {
insertTree(&(*root)->m_rs, n);
}
}
struct Node* getBinTree(FILE* fsrc) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
struct Node** root = (struct Node**)malloc(sizeof(struct Node*));
*root = (struct Node*)malloc(sizeof(struct Node));
int c, i;
while ((c = fgetc(fsrc)) != EOF) {
freq[c]++;
}
freq[255] = 1;
fclose(fsrc);
for (i = 0; i < 256; i++) {
if (freq[i] > 0) {
temp = createNode(freq[i], i);
insertTree(root, temp);
}
}
}
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->m_ls);
printf(" %d\n", root->m_freq);
inorder(root->m_rs);
}
return;
}
Your,
struct Node* getBinTree(FILE *fsrc)
is not returning anything.
You should enable compiler warnings, the compiler would have told you about that, the function is not returning a value, but you still assign it to tree in main().
But apart from that there is a serious problem with your code, a simple example
int main()
{
FILE *fsrc;
struct Node *tree = (struct Node*)malloc (sizeof(struct Node));
fsrc = fopen("src.txt","rb");
tree=getBinTree(fsrc);
inorder(tree);
return 1;
}
This single function has many problems,
You allocate new memory and point to it with tree, but you never use it because you overwrite the pointer here
tree = getBinTree(fsrc);
that causes a memory leak.
You don't check if the file was succesfuly opened, you must check
fsrc = fopen("src.txt", "rb");
if (fsrc == NULL)
return -1;
You don't need to cast malloc()
struct Node *tree = malloc(sizeof(*tree));
this is more robust, and easier to read.
You have to make sure that malloc() did not fail to allocate memory, when it does NULL is returned, so you need this when you do a malloc() that is actually required, for example in getBinTree()
struct Node *tree = malloc(sizeof(*tree));
if (tree == NULL)
return NULL;
i.e., copy malloc()'s behavior by returning NULL on failure.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct strqueue {
struct lnode *front;
struct lnode *back;
int length;
};
struct lnode {
char *item;
struct lnode *next;
};
StrQueue create_StrQueue(void) {
struct strqueue *sq = malloc(sizeof(struct strqueue));
sq->length = 0;
sq->front = NULL;
sq->back = NULL;
return sq;
}
void destroy_nodes(struct lnode *l) {
while (l!=NULL) {
struct lnode *c = l;
l=l->next;
free(c);
}
}
void destroy_StrQueue(StrQueue sq) {
destroy_nodes(sq->front);
free(sq);
}
void sq_add_back(StrQueue sq, const char *str) {
struct lnode *n = malloc(sizeof(struct lnode));
n->item = malloc(sizeof(char)*(strlen(str)+1));
strcpy(n->item, str);
n->next = NULL;
if (sq->length == 0) {
sq->front = n;
sq->back = n;
} else {
sq->back->next = n;
sq->back = n;
}
sq->length++;
}
char *sq_remove_front(StrQueue sq) {
if (sq->front == NULL) {
return NULL;
} else {
struct lnode *f = sq->front;
char *temp = sq->front->item;
sq->front = sq->front->next;
sq->length--;
//Delete the line below will not cause an error of not free all memory
free(f->item);
free(f);
return temp;
}
}
int sq_length(StrQueue sq) {
return sq->length;
}
Here I wanna make the strqueue like a linked list but when I use it, it always says that I am attempting to double free something. Which part of my code is wrong? Is there a memory leak or something wrong about the memory allocation?
In
struct lnode *f = sq->front;
char *temp = sq->front->item;
sq->front = sq->front->next;
sq->length--;
//Delete the line below will not cause an error of not free all memory
free(f->item);
free(f);
return temp;
It returns pointer temp to freed memory in free(f->item), reading the string through that pointer is undefined behaviour. And if you free it that is going to be the double free. Basically, the returned pointer is useless.
The fix would be to avoid doing free(f->item) in that function. The caller would need to free the pointer to the string after use.
Singly-linked list is best represented by:
struct lnode *head, **tail;
Initialized as:
head = NULL;
tail = &head;
In this case there is no need for special handling of an empty list on appending. Appending always is:
*tail = n;
tail = &n->next;
Removing from the front is:
struct lnode *n = head;
if(head) {
head = head->next;
if(!head)
tail = &head;
}
return n;
You could try this in char *sq_remove_front(StrQueue sq) :
if (f->item != NULL) {
free(f->item);
f->item = NULL;
}
if (f != NULL) {
free(f);
sq->front = NULL;
}
It would avoid performing free() twice on the pointers.
I am having trouble with inserting items in linked list. All the elements end up having the same *data content that is inserted in the last. The program compiles successfully. I use gcc and gdb.
I am new to coding so please mention troubles if any that you see in my programming style.
typedef struct Node{
void* data;
struct Node* next;
} *node;
node allocate(){
node current = malloc(sizeof(struct Node));
current->data = NULL;
current->next = NULL;
return current;
}
void insert(node *head, void *data){
// if head has no data then set the data on head and return
if(((*head)->data == NULL)&&((*head)->next == NULL)){
(*head)->data = data;
return;
}
node newHead = allocate();
newHead->data = data;
newHead->next = *head;
*head = newHead;
//printf("Node Data : %d\tNext Node Data : %d",
//*(int *)((*head)->data), *(int *)((*head)->data));
}
int main(int argc, char *argv[]){
node head = allocate();
int count = inputSequence(&head);
int *aod = calloc((size_t) count, sizeof(int));
generateAOD(head, aod);
if(checkJolly(aod, count) == TRUE)
printf("Jolly\n");
else
printf("Not Jolly\n");
return 0;
}
int inputSequence(node *input){
int *num = malloc(sizeof(int));
int count = 0;
while((scanf("%d", num) != EOF)){
insert(input, (void *)num);
count++;
}
traverse(*input, fn);
return count;
}
Your insert logic is non-existant. And you're literally making your life harder by attempting to manage a linked list in the fashion you're using.
The head pointer itself should indicate whether the list is empty. If it is NULL, its empty. If it isn't, there's data. Code the insertion logic accordingly.
And your inputSequence is utterly broken. It only allocates ONE data point, then uses the same data allocation for every insertion. You need one for each insertion.
First, change allocate() to accept the data being inserted. It will make the remaining code less cluttered:
node allocate(void *data)
{
node current = malloc(sizeof(*current));
current->data = data;
current->next = NULL;
return current;
}
Second, insert by allocating a new node as needed.
void insert(node *head, void *data)
{
node p = allocate(data);
p->next = *head;
*head = p;
}
Next, fix inputSequence() to properly allocate memory for each entry:
int inputSequence(node *input)
{
int count = 0;
int num = 0;
// note: check for number of params *successfully* parsed.
// if it isn't 1, its time to leave the loop.
while(scanf("%d", &num) == 1)
{
int *data = malloc(sizeof(num));
*data = num;
insert(input, data);
++count;
}
return count;
}
And lastly, make sure your head pointer is initially NULL in main().
int main(int argc, char *argv[])
{
node head = NULL;
// load linked list
inputSequence(&head);
// ... the rest of your code....;
return 0;
}
With the above, the logical answer of "Is my list empty" is simply if (!head) Further, this makes things like traversal trivial.
void traverse(node ptr, void (*pfn)(void *))
{
while (ptr)
{
pfn(ptr->data);
ptr = ptr->next;
}
}
Freeing the list is equally trivial:
void destroy(node *head)
{
while (*head)
{
node p = *head;
*head = p->next;
free(p->data);
free(p);
}
}
typedef struct Node{
void* data; // Make it as int or any other data type
struct Node* next;
} *node;
In function inputSequence() you are allocating memory for num at the very beginning and making node->data point to this memory each time you are adding a node. Hence data pointer of each node of your linked list points to the same memory location and hence contains the same value.
If you still want to continue with data as a void pointer, allocate num for each iteration of the while loop and pass this to insert function.
while((scanf("%d", num) != EOF)){
num = malloc(sizeof(int);
insert(input, (void *)num);
count++;
}