Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hello I have a problem with my code its shows this error: "Segmentation fault: 11" here is my code i'm trying to make a program that convert binary linked list to decimal using lists in C
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct cellule{
int b;
struct cellule* Next;
}Cellule;
typedef Cellule* liste;
int BinToEntier(liste a){
int n;
int j=0;
liste p=NULL;
for (p=a; p->Next!=NULL; p=p->Next) {
n+=(p->b)*pow(2,j);
j++;
}
return n;
}
int main() {
liste a=NULL;
liste p;
a= (liste) malloc(sizeof(Cellule));
p=a;
for (int i = 0; i < 4; i++) {
puts("enter b");
scanf("%i", &(p->b));
p=p->Next;
}
printf("%i\n", BinToEntier(a));
return 0;
}
In:
a= (liste) malloc(sizeof(Cellule));
a is not initialized to zero, yet in your loop you do a p=a;...p=p->Next. This will access undefined memory potentially causing a seg fault. (Note that scanf("%i", &(p->b)); can also cause the seg fault.)
Also in BinToEntier you forget to initialize n.
Your for loop in the function main() is causing the segmentation fault. Simply put, you are not allocating space for each node(i.e. Cellule) of the list, but allocating just the first element. Additionally, but almost as equally importantly, your assignment of the last node you append to the tail of the list is erroneous.
Consider switching to this usage given below.
int main() {
liste p=NULL;
liste *tp = &p;
for (int i = 0; i < 4; i++) {
*tp = malloc(sizeof(Cellule));
puts("enter b");
scanf("%i", &((*tp)->b));
*tp=&((*tp)->Next);
}
*tp = NULL;
printf("%i\n", BinToEntier(p));
return 0;
}
The code given above uses a variable tp, which is a pointer to a pointer to a Cellule. (i.e. list node) In effect, we update tp to show the "Next" attribute of the last Cellule in the list, and update it as we add new nodes to the list p.
Related
This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 4 years ago.
In the following code, I have two structs.
The first one is book which describes the number of pages of the book using page.
The second one is library which holds all the books using a pointer books, with the parameter num_book which tells the total number of books of the library.
The program can be compiled and run perfectly fine, and the printf result is OK.
But when I added the extra variable (e.g. int x = 1;) as shown in the code. I can still compile the program, but running the executable gives segmentation fault.
I have no idea why it is the case since everything seems to initialized properly. Thanks.
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int page;
} book;
typedef struct {
int num_book;
book *books;
} library;
int main() {
library *my_library;
int n = 5; // number of books in the library
// extra variable not used
// uncomment it gives segmentation fault
// int x = 1;
my_library->num_book = n;
my_library->books = (book *) malloc( (my_library->num_book) * sizeof(book) );
for(int i = 0; i < my_library->num_book; i++){
my_library->books[i].page = i+10;
printf("Book %d\n"
"Number of pages = %d\n",
i, my_library->books[i].page);
}
return 0;
}
Add this line after declaration of my_library
my_library = malloc(sizeof(*my_library));
In
library *my_library;
/* ... */
my_library->num_book = n;
// ^^^^^^^^^^ junk here
my_library has not been assigned (or initialized with) a usable value.
In C, you must allocate memory for your struct manually using malloc.
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int page;
} book;
typedef struct {
int num_book;
book *books;
} library;
int main() {
library *my_library = (library *) malloc(sizeof(library));
int n = 5; // number of books in the library
// extra variable not used
// uncomment it gives segmentation fault
int x = 1;
my_library->num_book = n;
my_library->books = (book *) malloc( (my_library->num_book) * sizeof(book) );
for(int i = 0; i < my_library->num_book; i++){
my_library->books[i].page = i+10;
printf("Book %d\n"
"Number of pages = %d\n",
i, my_library->books[i].page);
}
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have this line of code:
if (strcmp(n->data.name[i], searchName[i]) == 0)
I'm sure it's incorrect, how do i examine the first character of name which is stored in a linked list?(the error is "n->data.name[i]"
Thanks
This is the rest of the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct record
{
char name[20];
char surname[20];
char telephone[20];
}Record;
typedef struct node
{
Record data;
struct node *next;
}Node;
Node *head = NULL;
void search() {
Node *n = head;
Node *next = n;
int valid = 0;
int length2;
int valid2 = 0;
int valid3 = 0;
int count = 0;
char searchName[20];
printf(" Enter name, and/or surname, or tel no. : ");
gets();
gets(searchName);
length2 = strlen(searchName);
for (int i = 0; i < length2; i++)
{
valid2 = 0;
while (isspace(searchName[i]));
{
if (strcmp(n->data.name[i], searchName[i]) == 0)
{
valid2 = 1;
count++;
}
}
}
...
I assume you want the starting spaces in your search query to perform as a wild card. Your strcmp needs a minor update then: replace if (strcmp(n->data.name[i], searchName[i]) == 0) with if (strcmp(n->data.name + i, searchName +i) == 0)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
when i execute it the function do not work why?
#include<stdio.h>
struct stack{
int x[10];
int last;
};
void init(struct stack *s)
{
s->last=0;
}
void insert(struct stack *s)
{
int a;
while(a!=0)
{
int i;
printf("Enter the value\n");
scanf("%d",&i);
s->last++;
s->x[s->last]=i;
printf("%d",s->x[s->last]);
printf("enter 1 to continue 0 to exit\n");
scanf("%d",&a);
}
}
int main()
{
struct stack s;
int y,z;
printf("Trying out stacks\n");
printf("\n______________\n");
init(s);
insert(s);
return 0;
}
In function insert(), you declared
int a;
and then without initializing a you are doing the following,
while(a!=0)
will give Undefined Behaviour.
The following lines can leads buffer overflow,
s->last++;
s->x[s->last]=i; // no restriction applied on last
last can be more than 9 which can cause buffer overflow as x[10].
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am currently trying to solve a task, which is quite hard for me, a beginner to C, to handle and so i came to this point where I do not know what to do anymore.
My task is to implement polynomials with several functions....
The functions should be clear when you look at the code I think.
My exact problem is that i dont get a compiler error but a Segmentation Fault. I marked where my attempts to debug lead me to. But I have absolutely no clue on what I have to change. I hope someone can help me fix my code.
So here are the three code parts:
Number one: poly.c
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "poly.h"
struct poly_t {
unsigned degree;
int *coeffs;
};
//constructor: heap
poly_t *poly_alloc(unsigned degree){
poly_t *heap_p;
heap_p = malloc(sizeof(*heap_p)+(degree+1)*sizeof(int)); //or malloc(sizeof(*heap_p)*(degree+1)) furthermore not sure if degree or degree +1
}
//free heap
void poly_free(poly_t *p){
int *coeffs = p->coeffs;
free(coeffs);
free(p);
}
void poly_set_coeff(poly_t *p, unsigned deg, int coeff){
p->degree = deg;
p->coeffs += deg;
p->coeffs[deg] = coeff;
//does not work Segmentation Fault not sure what to do
//p->coeffs += deg;
//*p->coeffs = coeff;
printf("%d",*p->coeffs);
}
//different variations
poly_t *poly_linear(poly_t *p, int a1, int a0){
p->degree=1;
*p->coeffs=a1;
p->coeffs++;
*p->coeffs=a0;
p->coeffs--;
}
poly_t *poly_quadratic(poly_t *p, int a2, int a1, int a0){
p->degree=2;
*p->coeffs=a2;
p->coeffs++;
*p->coeffs=a1;
p->coeffs++;
*p->coeffs=a0;
p->coeffs-=2;
}
//evaluate using horner
int poly_eval(poly_t const *p, int x){
int d = p->degree;
int next;
int adr = *p->coeffs;
int *arr = p->coeffs;
int res = arr[d];
for(int i=0; i<=d; i++){
adr+=(d-i);
next = arr[adr];
adr-=(d-i);
res = res*x+next;
}
return res;
}
//constructor : .txt
poly_t *poly_alloc_d(){
//needs to be finished
}
Number Two: main.c
#include <stdlib.h>
#include <stdio.h>
#include "poly.h"
int main(int argc, char** argv){
if(argc<3){
fprintf(stderr, "syntax: %s x coeffs...", argv[0]);
return 1;
}
poly_t *p = poly_alloc(argc-3);
for(int i = 2; i<argc; i++){
int coeff = atoi (argv[i]);
poly_set_coeff(p, i-2, coeff);
}
return 0;//for debugging
int x=atoi(argv[1]);
int y=poly_eval(p,x);
poly_free(p);
printf("%d\n", y);
return 0;
}
And at last my header file:
poly.h
#ifndef POLY_H
#define POLY_H
/* unvollständiger Verbund */
typedef struct poly_t poly_t;
poly_t *poly_alloc(unsigned degree);
void poly_free(poly_t *p);
void poly_set_coeff(poly_t *p, unsigned deg, int coeff);
int poly_eval(poly_t const *p, int x);
#endif /* POLY_H */
I appreciate every help. I hope you can help me sort this out and please be patient with me a newbie to C...
Thanks in advance
You have not allocated or freed memory correctly, and the function didn't even return the pointer! I think you were trying to allocate one block of memory for the struct and the array it contains, but the struct does not contain an array: only a pointer to an array. You have to allocate them separately:
typedef struct {
unsigned degree;
int *coeffs;
} poly_t;
//constructor: heap
poly_t *poly_alloc(unsigned degree){
poly_t *heap_p;
heap_p = malloc(sizeof(*heap_p));
if (heap_p == NULL)
exit (1); // allocation error
heap_p->coeffs = malloc(degree * sizeof(int));
if (heap_p->coeffs == NULL)
exit (1); // allocation error
return heap_p;
}
//free heap
void poly_free(poly_t *p){
free(p->coeffs);
free(p);
}
There are other mistakes too, for example
p->coeffs += deg;
You mustn't play with the allocated memory pointer, you already did it correctly like this
p->coeffs[deg] = coeff;
although you can use an intermediate pointer if you want:
int *ptr = p->coeffs + deg;
*ptr = coeff;
Ok so I'm sure there's a simple fix that I'm missing, but right now my code is causing a segment fault on the line "A[i]->key = 0;." The Record* Item part is a necessity for the program, so I need to make it work this way for an assignment I'm working on, however if I do change it so that Item becomes a non-pointer typedef of Record, then I can use A[i].key no problem. I just need a nudge in the right direction so that I can make standInput correctly assign values to an array of pointers to records. Thanks!
Item.h:
#include "stdio.h"
#include "stdlib.h"
typedef int keyType;
struct Record
{
keyType key;
int other;
};
typedef struct Record* Item;
void standInput(Item *A, int n)
{
int i, input;
for(i = 0; i <= n-1; i++)
{
A[i]->key = 0;
printf("%d ", A[i]->key);
}
}
Main:
#include "stdio.h"
#include "stdlib.h"
#include "Item.h"
int main()
{
int n;
Item *A;
printf("Enter a length for the array: ");
scanf("%d", &n);
A = (Item*)malloc(n * sizeof(Item));
standInput(A, n);
return 0;
}
The values in A are all uninitialized, but you're using them as struct Record pointers anyway. If you want to have A continue holding pointers (rather than the structs directly), then you need to allocate space for A and for each item pointed to by A.
Note that Item is already a pointer!
You have to allocate space for the struct, not for the pointer:
A = (Item)malloc(n * sizeof(struct Record));
Note: If the typedef for pointer confuses you, don't use it ;)
A[i]->key means that A[i] is a pointer, but you just allocated an array, so use A[i].key.
Note: you have to change the type of A accordingly.
2nd solution: if you want A[i] to be a pointer, you have to fist allocate space for the pointers (as you do now), then for each pointer (in a loop) allocate space for the struct.
Your structure name is Record not Item. So you should use sizeof(struct Record).
Do it this way:
int main()
{
int n, i;
Item *A;
printf("Enter a length for the array: ");
scanf("%d", &n);
A = (Item*)malloc(n * sizeof(Item));
for(i=0; i<n; i++){
A[i] = (Item)malloc(sizeof(struct Record));
}
standInput(A, n);
return 0;
}