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;
Related
Okay, so the problem concerns adding values through function to structure. Honestly, I couldn't solve the problem (spent a lot of time trying), so I am asking for your help. While executing the program, I get a segmentation fault. It occurs while using the variables from stack stos.
typedef struct e {
int zaglebienie[100];
char *nazwa_funkcji[100];
int poz;
} *stack;
void put_on_fun_stack(int par_level, char *funame, stack stos) {
int i = stos->poz;
stos->zaglebienie[i] = par_level;
char *funkcja = strdup(funame);
stos->nazwa_funkcji[i] = funkcja;
stos->poz++;
}
int main() {
char *p = "makro";
stack stos;
stos->zaglebienie[0] = 0;
put_on_fun_stack(1, p, stos);
return 0;
}
You're declaring a pointer to stack but you're not allocating any memory to it.
And as already mentioned in the comments, using typedef with with a pointer will unnecessarily complicate your life.
So I suggest you create the struct stack and then in main declare a pointer to stack and allocate memory for it, somewhat like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct e {
int zaglebienie[100];
char *nazwa_funkcji[100];
int poz;
} stack;
void put_on_fun_stack(int par_level, char *funame, stack *stos)
{
int i = stos->poz;
stos->zaglebienie[i] = par_level;
char *funkcja = strdup(funame);
stos->nazwa_funkcji[i] = funkcja;
stos->poz++;
}
int main(void)
{
char *p = "makro";
// calloc to initialize stos variables to 0
stack *stos = calloc(sizeof(stack), 1);
printf("stos->poz before: %d\n", stos->poz);
put_on_fun_stack(1, p, stos);
printf("stos->poz after: %d\n", stos->poz);
printf("stos->nazwa_funkcji[0]: %s\n", stos->nazwa_funkcji[0]);
free(stos->nazwa_funkcji[0]);
free(stos);
return 0;
}
Output:
stos->poz before: 0
stos->poz after: 1
stos->nazwa_funkcji[0]: makro
I'm having an issue understanding this, my code below:
#include <stdio.h>
#include <stdlib.h>
typedef struct mee test;
typedef struct aa fill;
struct aa {
int c;
fill *point;
};
struct mee {
char name;
fill **a;
int b;
};
static fill **store;
static fill *talloc(int tsize);
static int mem;
static int ptr;
static fill *talloc(int tsize)
{ int temp;
temp = ptr;
ptr++;
mem = mem + tsize;
store = realloc(store, mem*sizeof(fill));
store[temp] = malloc(sizeof(fill));
return store[temp];
}
int main() {
test *t;
t = malloc(sizeof(test));
t->a = malloc(sizeof(fill *)*10);
printf("where\n");
for(int i= 0; i < 10; i++) {
t->a[i] = talloc(1);
}
printf("%d\n", store[9]->c); //Problem here
return 0;
}
excuse the terrible names, just some test code for a larger project. This code compiles and runs fine. if I set the code:
printf("%d\n", store[9]->c);
store[0-7] I get 0 as the output, though why does 8-9 give me some gibberish negative number? I'm assuming its a loss it the pointer somewhere.
How can I correct this?
For some background, this is to store pointers to struct in a array so I can free them a lot easier later.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have been trying to call this function, but I keep getting the error "identifier not found" (yes, I know my variable names aren't the most practical).
#include <stdio.h>
#include <stdlib.h>
typedef struct _POOL
{
int size;
void* memory;
} Pool;
int main()
{
printf("Enter the number of bytes you want to allocate\n");
int x = getchar();
allocatePool(x);
return 0;
}
Pool* allocatePool(int x)
{
Pool* p = (Pool*)malloc(x);
return p;
}
Maybe what you want to do should look like this:
#include <stdio.h>
#include <stdlib.h>
typedef struct pool
{
int size;
void* memory;
} pool;
pool allocatePool(int x);
int main (int argc, char *argv[])
{
int x = 0;
pool *p = NULL;
printf("enter the number of bytes you want to allocate//>\n");
if (scanf("%d", &x) == 1 && x > 0 && (p = allocatePool(x)) != NULL)
{
// Do something using p
// ...
// Treatment is done, now freeing memory
free(p->memory);
free(p);
p = NULL; // Not useful right before exiting, but most often good practice.
return 0;
}
else
{
// Show a message error or do an alternative treatment
return 1;
}
}
pool allocatePool(int x)
{
pool *p = malloc(sizeof(pool));
if (p != NULL)
{
p->memory = malloc(x);
p->size = (p->memory == NULL) ? 0 : x;
}
return p;
}
I think your program should look like this:
#include <stdio.h>
#include <stdlib.h>
typedef struct _Pool
{
int size;
void* memory;
} Pool;
Pool* allocatePool(int x)
{
static Pool p;//no pointer here you also need memory for your integer or you have to allocate memory for the integer too
p.size=x;
p.memory=malloc(x);//just allocate memory for your void pointer
return &p;//return the adress of the Pool
}
int main()
{
printf("enter the number of bytes you want to allocate//>\n");
int x;
scanf("%d", &x);//if you use getchar() for reading you pass the ascii value of the number not the normal number
allocatePool(x);
return 0;
}
I'm fully prepared to be told that I'm doing something stupid/wrong; this is what I expect.
I'm getting a feel for structures and coming a cropper when it comes to accessing the fields from the pointers. Code to follow.
matrix.h:
#ifndef MATRIX_H_INCLUDED
#define MATRIX_H_INCLUDED
#include <stdlib.h>
typedef struct
{
size_t size;
int* vector;
} vector_t;
#endif // MATRIX_H_INCLUDED
main.c:
#include <stdio.h>
#include <stdlib.h>
#include "matrix.h"
vector_t* vector_new(size_t size)
{
int vector[size];
vector_t v;
v.size = size;
v.vector = vector;
return &v;
}
int main(int argc, char* argv[])
{
vector_t* vec = vector_new(3);
printf("v has size %d.\n", vec->size);
printf("v has size %d.\n", vec->size);
return EXIT_SUCCESS;
}
So this is a very simple program where I create a vector structure of size 3, return the pointer to the structure and then print its size. This, on the first print instance is 3 which then changes to 2686668 on the next print. What is going on?
Thanks in advance.
You are returning a pointer to a local variable v from vector_new. This does not have a slightest chance to work. By the time vector_new returns to main, all local variables are destroyed and your pointer points to nowhere. Moreover, the memory v.vector points to is also a local array vector. It is also destroyed when vector_new returns.
This is why you see garbage printed by your printf.
Your code has to be completely redesigned with regard to memory management. The actual array has to be allocated dynamically, using malloc. The vector_t object itself might be allocated dynamically or might be declared as a local variable in main and passed to vector_new for initialization. (Which approach you want to follow is up to you).
For example, if we decide to do everything using dynamic allocation, then it might look as follows
vector_t* vector_new(size_t size)
{
vector_t* v = malloc(sizeof *v);
v->size = size;
v->vector = malloc(v->size * sizeof *v->vector);
return v;
}
(and don't forget to check that malloc succeeded).
However, everything that we allocated dynamically we have to deallocate later using free. So, you will have to write a vector_free function for that purpose.
Complete re-write of answer to address your question, and to provide alternate approach:
The code as written in OP will not compile: &v is an illegal return value.
If I modify your code as such:
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
size_t size;
int* vector;
} vector_t;
vector_t* vector_new(size_t size)
{
int vector[size];
vector_t v, *pV;
pV = &v;
pV->size = size;
pV->vector = vector;
return pV;
}
int main(int argc, char* argv[])
{
vector_t* vec = vector_new(3);
printf("v has size %d.\n", vec->size);
printf("v has size %d.\n", vec->size);
getchar();
return EXIT_SUCCESS;
}
It builds and runs, but returns unintended values for vec->size in main() due to the local scope of that variable in the function vector_new.
Recommend creating globally visible instance of your struct, and redefine vector_new() to int initVector(void):
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
typedef struct
{
size_t size;
int* vector;
} vector_t;
vector_t v, *pV;//globally visible instance of struct
int initVector(void)
{
int i;
pV->size = SIZE;
pV->vector = calloc(SIZE, sizeof(int));
if(!pV->vector) return -1;
for(i=0;i<SIZE;i++)
{
pV->vector[i] = i;
}
return 0;
}
int main(int argc, char* argv[])
{
int i;
pV = &v; //initialize instance of struct
if(initVector() == 0)
{
printf("pV->size has size %d.\n", pV->size);
for(i=0;i<SIZE;i++) printf("pV->vector[%d] == %d.\n", i, pV->vector[i]);
}
getchar(); //to pause execution
return EXIT_SUCCESS;
}
Yields these results:
You still need to write a freeVector function to undo all the allocated memory.
Why do I get segmentation fault in this function:
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
vec_t mtrx_multiple (sparse_mat_t a, vec_t c) {
vec_t result;
int i;
result.n = a.n;
printf("result.n: %d\n", result.n);
result.vec = malloc(a.n * sizeof *result.vec);
for(i=0; i<a.n; i++)
result.vec[i] = c.vec[i] * a.a[a.ja[i]];
return result;
}
The structure is:
typedef struct {
int n;
int *vec;
} vec_t;
typedef struct {
int *a;
int *ia;
int *ja;
int n;
} sparse_mat_t;
Thanks for help
I suspect the problem is with a.a[a.ja[i]], you should try verifying the values a.ja[i] before using them to index a.a.
It would be useful to know how a is initialised, and also on which line the segfault occurs.
Malloc could be failing and returning null.
a.ja[i] might not be between 0 and n. What is the ja array supposed to represent, anyway?
Our speculating isn't going to produce the answer. Running your program under a debugger will.
I suspect this is the line where the trouble is:
result.vec = malloc(a.n * sizeof *result.vec);
for(i=0; i<a.n; i++)
result.vec[i] = c.vec[i] * a.a[a.ja[i]];
The reason is that you are not mallocing for each result.vec[i]..
Can you confirm this?
Edit:
Thanks Alok and Devel for informing me about my error...
What does sizeof *result.vec return? Admittedly it looks confusing as if the precedence between sizeof gets mixed with the *...
Hope this helps,
Best regards,
Tom.
typedef struct {
int n;
int *vec;
} vec_t;
int main(int argc, char **argv) {
vec_t result;
int i;
int size;
result.n = 5;
size = result.n * sizeof *result.vec;
result.vec = malloc(size);
for(i=0; i<result.n; i++) {
result.vec[i] = i;
}
return i;
}
I have to agree with Autopulated, this version of your code runs just fine, the only thing I left out in this refactoring is the a and c related stuff. I would check that a and c are being initialized properly.