How to allocate memory? - c

I am trying to create a linked list in my program and I am not able to allocate memory to the structure pointer using malloc(). How do I allocate memory to variables in GCC? The sample program is given below. How to make it work in gcc?
#include<stdio.h>
#include <alloc.h>
struct node
{
int data;
struct node * link;
};
void insert (struct node *p, int d)
{
struct node *temp;
temp = malloc(sizeof(struct node));
temp->data=d;
temp->link=NULL;
if(p==NULL)
{
p=temp;
}
else{
while(p->link!=NULL)
p=p->link;
p->link=temp;
}
}
void disp(struct node *p)
{
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->link;
}
}
int main()
{
struct node *p;
p=NULL;
insert(p,7);
insert(p,9);
disp(p);
}
The error I'm encountering is:
Line 18: error: alloc.h: No such file or directory
In function 'insert':
Line 13: warning: incompatible implicit declaration of built-in function 'malloc'

malloc is in <stdlib.h>. Include that.
Reading the man page for that function would have given you that information. It's not compiler-dependent.

malloc is declared in <stdlib.h>, so that's what you want to #include.

The definition of malloc is in the stdlib.h file:
#include <stdlib.h>
instead of alloc.h.

Like the others say: your error occurs because you have to include stdlib.h instead of alloc.h
To get your list printed, you have to modify p in insert. Currently, you're passing NULL every time you call insert. Change your code that way (pass a pointer-to-pointer to insert):
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node * link;
};
/* note **p instead of *p */
void insert (struct node **p, int d)
{
struct node *temp;
temp = malloc(sizeof(struct node));
temp->data=d;
temp->link=NULL;
if(*p==NULL)
{
*p=temp;
}
else{
while((*p)->link!=NULL)
*p=(*p)->link;
(*p)->link=temp;
}
}
void disp(struct node *p)
{
while(p!=NULL)
{
printf("%d\n",p->data);
p=p->link;
}
}
int main()
{
struct node *p;
p=NULL;
insert(&p,7);
insert(&p,9);
disp(p);
}
and it will print
7
9

Related

memory allocation/pointer troubles or bad algorithm in C

I have writen a simple code in C. What I am trying to accomplish is given a string [similar to html] I am creating node pointer object. May be its called serialization or something but not sure.
For example, I have string abccbccacca in which a tag has two immediate children ccacc and bccb going further recursively deep bccb tag b also has two children so two = c and each c are siblings together.
But this lines are in my thinking not doing what they suppose to.
struct node *temp=malloc(sizeof(struct node));
struct node *t=n+i;
t=temp;
parse(arr,l,r,(struct node *)n+i);
What I am doing above is simply allocate n+i-th sibling and passing recursively.
I also tried like this
(n+i)=malloc(sizeof(struct node));
parse(arr,l,r,(struct node *)n+i);
But the above does not compile and give error that lvalue should be ...
So I believe algorithm makes sense but I may need pointer to pointer for allocation if I want this to output something
struct node *no=n->ch;
struct node *no1=no->ch;
printf("\n%c\n",no1[2].c);
This is full code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stddef.h>
#include <string.h>
#include <malloc.h>
struct node {
char c;
struct node *ch;
};
int chcmp(char a,char b)
{
if(a==b)
return 1;
return 0;
}
void parse(char *arr,int l,int r,struct node *n)
{
if(arr[l]==arr[r])
{
n->c=arr[r];
//printf(" &%c %c ",*(arr+r),*(arr+l));
n->ch=malloc(sizeof(struct node));
r--;
l++;
printf("%c",n->c);
parse(arr,l,r,n->ch);
}
//printf("\n");
int i=0;
while(r>l)
{
if(arr[r]!=arr[l])
{
//printf("[%c %c] %d\n",arr[r],arr[l],l);
r--;
}
else
{
struct node *temp=malloc(sizeof(struct node));
struct node *t=n+i;
t=temp;
parse(arr,l,r,(struct node *)n+i);
l=r+1;
r=strlen(arr);
i++;
}
}
}
int main()
{
struct node *n=malloc(sizeof(struct node));
char *arr="abccbccacca";
parse(arr,0,strlen(arr)-1,n);
struct node *no=n->ch;
struct node *no1=no->ch;
printf("\n%c\n",no1[2].c);
}

How to initialize a pointer outside of main?

I am trying to implement nodelist in c:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int value;
void *next;
} node_t;
void printlist(node_t*head){
for(node_t*i=head;i;i=i->next)
printf("%i\n",i->value);
}
node_t create(int value){
node_t *ret = malloc(sizeof(node_t));
ret->value=value;
ret->next=0;
return *ret;
}
int main(){
int i=0;
node_t*head=0;
for(node_t*tmp;i++<10;head=tmp)
{
*tmp=create(i+100);
tmp->next=head;
}
printlist(head);
}
and in the for loop, I am using node_t* pointer which is assign to already initialized (via malloc) struct outside in create function. But the program emits:
warning: ‘tmp’ may be used uninitialized in this function [-Wmaybe-uninitialized]
*tmp=create(i+100);
Command terminated
So how to assign a dereferenced pointer to already initialized data in c?
When you first enter the loop, tmp doesn't point to anything. Because of that, it's invalid to dereference the pointer.
Also, you have a memory leak in create. You dynamically allocate memory for a node but then return a copy of that node, leaving nothing to point to the allocated memory.
You can fix these issues by returning a pointer from the function:
node_t *create(int value){
node_t *ret = malloc(sizeof(node_t));
ret->value=value;
ret->next=0;
return ret;
}
And subsequently saving that pointer in tmp in the calling function:
tmp=create(i+100);
For starters the function create should return pointer to the created dynamically node. Otherwise you will be unable to free allocated nodes because the function returns a copy of a created node.
So rewrite the function at least like
node_t * create(int value){
node_t *ret = malloc(sizeof(node_t));
ret->value=value;
ret->next=0;
return ret;
}
In the for loop in main you are using an uninitialized pointer tmp. So with the function implementation of create as you defined it the loop invokes undefined behavior due to the underlined assignment
for(node_t*tmp;i++<10;head=tmp)
{
*tmp=create(i+100);
^^^^^^^^^^^^^^^^^^
tmp->next=head;
}
So after changing the function create change the loop like
for(node_t*tmp;i++<10;head=tmp)
{
tmp=create(i+100);
tmp->next=head;
}
Here is your updated program.
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int value;
void *next;
} node_t;
void printlist(node_t*head){
for(node_t*i=head;i;i=i->next)
printf("%i\n",i->value);
}
node_t * create(int value){
node_t *ret = malloc(sizeof(node_t));
ret->value=value;
ret->next=0;
return ret;
}
int main(){
int i=0;
node_t*head=0;
for(node_t*tmp;i++<10;head=tmp)
{
tmp=create(i+100);
tmp->next=head;
}
printlist(head);
}
Its output is
110
109
108
107
106
105
104
103
102
101

Why am I getting Segmentation fault (core dumped) or bus error (core dumped) when trying to populate a struct?

So I am trying to use a pointer to a struct of MonsterAttacks as the data that belongs to an element of a linked list. In order to do this I try to populate a struct of MonsterAttacks and then pass that along with a null ptr to a next node to a function called create. However somewhere in the populate method a segmentation fault error occurs. I am working with three files list_demo.c, linked_list.h and linked_list.c. I will build all the the functions that make up a fully functioning linked list, well hoping I can as soon as I get pass this error. Been dealing with this error for about two days and I showed my professor and he could not figure out why its happening, it seems to come from the populate function. I have tried to return a pointer to a strut in which case I get a bus error, and I have tried almost every variation of getting input and storing it on the strut. I even deleted the function and tried to populate it in main, but nothing works. I am new to C and my professor helped me out for about an hour debug this problem and he finally gave up, so any help would be appreciated.
list_demo.c
#include <stdio.h>
#include "linked_list.h"
#include <stdlib.h>
void populate(struct MonsterAttacks *m){
printf("Enter the name for the Monster \n");
scanf("%40s",m->monsterName);
puts("What is his/her attack location?");
scanf("%40s",m->attackLocation);
puts("What are the number of victims this monster has demolished?");
scanf("%ud", &m->numOfVictims);
m->attackID = 0;
}
int main(void)
{
node* tmp = NULL;
struct MonsterAttacks *tmpMonst = (struct MonsterAttacks *)
malloc(sizeof(struct MonsterAttacks));
if(tmpMonst == NULL){
printf("Error allocating memory");
}
else
populate(tmpMonst);
node *head = create(tmpMonst,tmp);
free(tmpMonst);
return 0;
}
linked_list.h
#ifndef LINKED_LIST
#define LINKED_LIST
typedef struct node{
struct MonsterAttacks *monsterAttack;
struct node* next;
} node;
struct MonsterAttacks{
unsigned int attackID;
char monsterName[41];
char attackLocation[41];
unsigned int numOfVictims;
};
/*
create a new node
initialize the data and next field
return the newly created node
*/
node* create(struct MonsterAttacks *m,node* next);
#endif
linked_list.c
// from zentut.com, heavily adapted
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "linked_list.h"
/*
create a new node
initialize the data and next field
return the newly created node
*/
node* create(struct MonsterAttacks *m,node* next)
{
node* new_node = (node*)malloc(sizeof(node));
if(new_node == NULL)
{
printf("Error creating a new node.\n");
exit(0);
}
new_node->monsterAttack->attackID = 0;
new_node->next = next;
strncpy(new_node->monsterAttack->monsterName,m->monsterName,41);
strncpy(new_node->monsterAttack->attackLocation, m->attackLocation, 41);
new_node->monsterAttack->numOfVictims = m->numOfVictims;
return new_node;
}
Btw running on Red Hat using gcc compiler
new_node->monsterAttack->attackID = 0;
Allocating memory for new_node does not allocate memory for the MonsterAttacks struct inside it. That is why dereferencing monsterAttack to get its attackID is causing a seg fault.
A minimal working code
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
// Moved the two structs out to make a minimal reproducible code
/* #include "linked_list.h" */
struct MonsterAttacks{
unsigned int attackID;
char monsterName[41];
char attackLocation[41];
unsigned int numOfVictims;
};
typedef struct node{
struct MonsterAttacks *monsterAttack;
struct node* next;
} node;
void populate(struct MonsterAttacks *m){
printf("Enter the name for the Monster \n");
scanf("%40s",m->monsterName);
puts("What is his/her attack location?");
scanf("%40s",m->attackLocation);
puts("What are the number of victims this monster has demolished?");
scanf("%ud", &m->numOfVictims);
m->attackID = 0;
}
node* create(struct MonsterAttacks *m,node* next)
{
node* new_node = (node*)malloc(sizeof(node));
if(new_node == NULL)
{
printf("Error creating a new node.\n");
exit(0);
}
// Just add this line
new_node->monsterAttack = malloc(sizeof (struct MonsterAttacks));
new_node->monsterAttack->attackID = 0;
new_node->next = next;
strncpy(new_node->monsterAttack->monsterName,m->monsterName,41);
strncpy(new_node->monsterAttack->attackLocation, m->attackLocation, 41);
new_node->monsterAttack->numOfVictims = m->numOfVictims;
return new_node;
}
int main(void)
{
node* tmp = NULL;
struct MonsterAttacks *tmpMonst = (struct MonsterAttacks *)
malloc(sizeof(struct MonsterAttacks));
if(tmpMonst == NULL){
printf("Error allocating memory");
}
else {
populate(tmpMonst);
}
node *head = create(tmpMonst,tmp);
printf("Name: %s\n", tmpMonst->monsterName);
printf("num victim: %d\n", tmpMonst->numOfVictims);
free(tmpMonst);
return 0;
}
When you allocate memory for new_node in create(...), you allocate memory on the heap for a structure of type node to hold all the variables it contains. In this case, monsterAttack in node is initially a pointer to a struct that is pointing to nowhere. You need to explicitly allocate memory for the monsterAttack pointer to point to.
Edit: #bruceg pointed out the lack of semicolon, this malloc isn't the issue. #lightalchemist have highlighted that the second one is the fault.
struct MonsterAttacks *tmpMonst = (struct MonsterAttacks *);
malloc(sizeof(struct MonsterAttacks));
Your malloc call is wrong, malloc allocates and returns a pointer to the memory. You ignore/discard the pointer value.
Later code seems to assume that tmpMonst points to this allocated memory but there is no link between the two.
Try struct MonsterAttacks *tmpMonst = malloc(sizeof(struct MonsterAttacks));

segmentation error in ubuntu

Please tell me why the segmentation error is there in my program there is no error .
I also tried to debug it but it never goes inside the for statement.
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node* link;
} *start;
main()
{
int i,n,m;
start=NULL;
printf("enter the number of nodes you want");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the element you want to insert");
scanf("%d",&m);
create_list(m);
}
}
create_list(int data)
{
struct node *q,*temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=data;
temp->link=NULL;
if(start==NULL)
start=temp;
else
{
while(q->link!=NULL) q=q->link;
q->link=temp;
}
}
You forgot to initialize q before using it:
q = start;
while(q->link!=NULL)
1.You haven't initialized q in create_list() and used it -
while(q->link!=NULL)
Intialize q=start; before this loop.
2.Also free the allocated memory for temp in function.
3.main() should be int main(void) and what is type of create_list? Declare its prototype before main.
In the function create_list local pointer q was not initialized
struct node *q,*temp;
^^^
However it is accessed in the loop
while(q->link!=NULL)
I think you mean the following
else
{
q = start;
while ( q->link != NULL ) q = q->link;
q->link = temp;
}
Take into account that the function should be declared before its usage. Place it declaration for example before main. And its return type shall be void and specified explicitly. Also function main shall have return type int.
For example
void create_list( int data );
int main( void )
{
//...
And it is a good idea to free all dynamically allocated memory before exiting the program.
Also header <malloc.h> is not a standard C header. You should use <stdlib.h> instead.
After all suggestions from the above it will be clearly in the future if you try to show some work of your clear codding and to respect the minimum standard.
Here is a way of how should be looking your code:
#include<stdio.h>
#include<stdlib.h> /* You need stdlib not malloc */
void create_list(int data); /* If you don't declare your function the compiler doesn't know nothing about create_list */
struct node{
int data;
struct node* link;
}*start;
int main(void){ /* Here return type of main is int and if no arg needed should be used void */
int i,n,m;
start=NULL;
printf("enter the number of nodes you want");
if((scanf("%d",&n)) != EOF) /* always check scanf's return */
for(i=0;i<n;i++){
printf("enter the element you want to insert");
if((scanf("%d",&m)) != EOF) /* here the same: always check scanf's return */
create_list(m);
}
return 0; /* return of main should be 0 or one of the following: EXIT_SUCCESS or EXIT_FAILURE, but 0 will be ok because it is standard*/
}
void create_list(int data){ /* here should be explicit what kind of function is */
struct node *q,*temp;
temp=(struct node *)malloc(sizeof(struct node)); /* if you allocate memory dynamically ..... */
temp->data=data;
temp->link=NULL;
if(start==NULL){
start=temp;
}else{
q = start;
while(q->link!=NULL){
q=q->link;
q->link=temp;
}
}
free(temp); /* .....then always free it */
}

C Stack pointing to Address?

I am new to C. I have implemented a simple stack with some structs and what not. I have posted the entire code below. The problem section is commented.
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node *next;
} Node;
typedef struct Stack{
Node *top;
int size;
} Stack;
/* Function Prototypes */
void push(Stack *sPtr, int data);
int pop(Stack *sPtr);
void create(Stack *sPtr);
int main(void)
{
static Stack first;
create(&first);
push(&first,4);
push(&first,3);
push(&first,2);
printf("%d\n",pop(&first));
printf("%d\n",pop(&first));
printf("%d\n",pop(&first));
exit(1);
}
void push(Stack *sPtr, int data)
{
struct Node newNode;
newNode.data = data;
newNode.next = sPtr->top;
sPtr->top = &newNode;
sPtr->size++;
printf("%d\n",sPtr->top->data);
}
int pop(Stack *sPtr)
{
struct Node *returnNode = sPtr->top;
struct Node *topNode = sPtr->top;
if(sPtr->size != 0){
sPtr->top = topNode->next; /* =============PROBLEM?=============== */
return returnNode->data;
}
else{
printf("Error: Stack is Empty!\n");
return -1;
}
}
void create(Stack *sPtr)
{
sPtr->size = 0;
sPtr->top = NULL;
}
The output of this code is
4
3
2
2
8103136
680997
So obviously, it is pulling off the top node, and then printing the addresses of the next two nodes, instead of their data.
But why is it doing this? As far as I know (which is little) preforming this operation
sPtr->top = topNode->next;
should tell the program to make top now point to to topNode.next. But instead, it seems to be returning the address. What's going on here?
In your push() function, you're creating a new struct Node and adding it to your stack. However, the node is a local variable within the scope of push()--allocated on the stack (not your stack, the call stack), and will be gone when push() returns.
What you want to do is create the node on the heap, which means it will still be there after push() returns.
Since you're coding in C, you'll want to do something like:
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
Since you're now dealing with heap-allocated memory, you'll need to make sure that at some point it gets freed (somewhere) using free().
You're also not decrementing size as Jonathan has pointed out.
One trouble is that pop() never decrements size, so size is really 'number of elements ever pushed onto stack', not 'the number of elements in the current stack'.
int pop(Stack *sPtr)
{
struct Node *returnNode = sPtr->top;
struct Node *topNode = sPtr->top;
if (sPtr->size != 0)
{
sPtr->top = topNode->next;
sPtr->size--;
return returnNode->data;
}
else
{
fprintf(stderr, "Error: Stack is Empty!\n");
return -1;
}
}
Another trouble, as pointed out by unluddite in his answer is that you are not pushing data correctly. You need both fixes to be safe. There might still be other problems (such as not freeing memory correctly — or at all), but these two will get you a long way.

Resources