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.
Related
Feel like im taking crazy pills just trying to do literally the simplest stuff I can imagine in C. Any help would be extremely appreciated. why does this work?
#include <stdio.h>
#include <stdlib.h>
#define Q_LIMT 100
typedef struct servers
{
int id;
int num_in_Q;
int server_status;
}SERVER;
void initialize(SERVER *s);
void initialize(SERVER *s)
{
int i=0,j=0;
for(i=0; i<2; i++) { //i=0; i=1
s[i].id = i; // 0, 1
s[i].num_in_Q = i*i + 1; // 1, 2
s[i].server_status = i+i + 2; // 2, 4
} // the bracket was missing
}
int main()
{
int i;
SERVER serv[2];
initialize(serv);
for(i=0; i<2; i++) {
printf("server[%d].id = %d\n", i, serv[i].id);
printf("server[%d].num_in_Q = %d\n", i, serv[i].num_in_Q);
but this throws away the initialized struct?
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
'''
int POINTERS_PER_INODE = 5;
struct Inode {
int valid;/* 0 == invalid, 1 == valid*/
int size;
int Blocks [5];
};
int InodeToString(char * InodeString, struct Inode iNode){
char * blockBuffer;
sprintf(InodeString, "%d", iNode.valid);
int i;
for (i = 0; i < POINTERS_PER_INODE; i++){
blockBuffer = malloc(8);
sprintf(blockBuffer, "%d", iNode.Blocks[i]); //no valid pointers yet
strcat(InodeString,blockBuffer);
free(blockBuffer);
}
return 0;
}
int initializeInode(struct Inode iNode){
int i;
for (i = 0; i < POINTERS_PER_INODE; i++){
iNode.Blocks[i] = -1; //no valid pointers yet
}
iNode.valid = 0; //initialized as invalid inode
return 0;
}
int main() {
struct Inode iNode1;
initializeInode(iNode1);
char * InodeString;
InodeString = malloc(20);
InodeToString(InodeString, iNode1);
printf("%s", InodeString);
free(InodeString);
iNode1.valid = 1;
InodeString = malloc(20);
InodeToString(InodeString, iNode1);
printf("%s", InodeString);
return 0;
}
This is test code btw, so the includes probably dont make sense. stack overflow says I dont have enough details so I guess I have to keep typing sentences. Let me know if theres any details that would make this more clear. its for a basic super simplified file system simulation project. it seemed in a previous version when I initialized the inode outside of the function, I was able to pass the string into the string function, assign it values, not use it as the return value and still end up on the other side of the function with an updated string.
As is normal in C, arguments to a function are passed by value. The object called iNode in initializeInode is local to that function, and changes to it have no effect on any other object in the program. If you want a function to modify an object that's local to the caller, you have to pass a pointer to it, and dereference that pointer to get at the caller's object.
So what you probably want is:
int initializeInode(struct Inode *iNode){
int i;
for (i = 0; i < POINTERS_PER_INODE; i++){
iNode->Blocks[i] = -1; //no valid pointers yet
}
iNode->valid = 0; //initialized as invalid inode
return 0;
}
int main() {
struct Inode iNode1;
initializeInode(&iNode1);
// ...
}
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;
I'm getting this error on line #4 which says 'invalid initializer'. I know what the error means, but I can't work out why i'm getting the error. I've tried all sorts of combinations of pointers and values, but it doesn't seem to want to work. Any help / feedback for the code would be greatly appreciated.
Note: I plan to have a 2D array for the chessboard, which mean 64 ints of memory malloc'd.
The printf is there to keep the compiler happy and show me whether at [4][2] there is a '0'.
int *newBoard();
int main(int argc, char *argv[]) {
int *chessBoard[7][7] = *newBoard();
printf ("%d", chessBoard[4][2]);
return EXIT_SUCCESS;
}
int *newBoard() {
int counter = 0;
int *blankBoard = malloc(sizeof((int) * TOTALSPACES));
while (counter < TOTALSPACES) {
blankBoard[counter] = VACANT;
counter++;
}
return blankBoard;
}
newBoard returns an array of TOTALSPACES ints. int *chessBoard[7][7] = *newBoard(); LHS is a 7x7 array of int pointers (not ints). RHS is what, the contents of of an int pointer returned by the call? (what do you think the * infront of the call to newBoard() is doing?
Either int *newBoard = newBoard(); (to use heap memory) or int newBoard[7][7]; (to use stack memory) would work. You are trying to do half of each!
int *chessBoard[7][7] stands for an 2D array(7*7), each element type is int*;
but *newBoard() stand for an int element.
#include <stdio.h>
#include <stdlib.h>
#define TOTALSPACES 8*8
#define VACANT '0'
void *newBoard();
int main(int argc, char *argv[]) {
int (*chessBoard)[8][8] = newBoard();
printf ("%d", (*chessBoard)[4][2]);//48 : '0'
return EXIT_SUCCESS;
}
void *newBoard() {
int *blankBoard = malloc(sizeof(int) * TOTALSPACES);
int counter = 0;
while (counter < TOTALSPACES)
blankBoard[counter++] = VACANT;
return blankBoard;
}
typedef struct Carta* BAR_tppCarta
BAR_tppCarta * BAR_CriarBaralho ()
{
int i;
int j;
int k=0;
BAR_tppCarta *baralho;
baralho = (BAR_tppCarta *) malloc(NUM_CARTAS*sizeof(BAR_tppCarta));
if(!baralho)
return NULL;
for(i=COPAS;i<=ESPADA;i++)
for(j=AS;j<=KING;j++)
{
baralho[k]->naipe = i;
baralho[k]->valor = j;
k++;
}
return baralho;
}
when I call this function in another module, using
BAR_tppCarta *baralho = BAR_CriarBaralho();
The windows stop working, like a debug error.
Can anyone help me please?
Very thanks!
Alessandro
BAR_tppCarta is just a pointer, so all you are returning is an array of uninitialised pointers (and you are also stomping over memory). I suspect that this line:
typedef struct Carta* BAR_tppCarta;
should probably be:
typedef struct Carta BAR_tppCarta;
and these two lines:
baralho[k]->naipe = i;
baralho[k]->valor = j;
should be:
baralho[k].naipe = i;
baralho[k].valor = j;
Alternatively you can keep the original definition of BAR_tppCarta as
typedef struct Carta* BAR_tppCarta;
and then allocate memory for each instance:
for(i=COPAS;i<=ESPADA;i++)
for(j=AS;j<=KING;j++)
{
baralho[k] = malloc(sizeof(struct Carta));
baralho[k]->naipe = i;
baralho[k]->valor = j;
k++;
}
although I would advise against this on the grounds of complexity unless you have a good reason to do it this way.
I'm teaching myself C since my uni seems to be obsessed with java, so im writing a stack implementation of type int (ill worry about making it generic later). I came across an error that makes not sense to me, missing ';' before 'type'. As far as i can tell my syntax is right, if it is not please do tell. Anyways here is my code:
stack.h
typedef struct{
int *elements;
int size;
int capacity;
}Stack;
void newStack(Stack *s);
void delStack(Stack *s);
void pushToStack(Stack *s, int value);
int popFromStack(Stack *s);
stack.c
#include "stack.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
void newStack(Stack *s){
s->size = 0;
s->capacity = 4;
s->elements = (int*) malloc(4 * sizeof(int));
assert(s->elements != NULL); // allocation worked?
}
void delStack(Stack *s){
free(s->elements);
}
void pushToStack(Stack *s, int value){
if(s->size == s->capacity){
s->size *= 2;
s->elements = (int *) realloc(s->elements, s->size * sizeof(int));
assert(s->elements !=NULL); //reallocation worked?
}
s->elements[s->size] = value;
s->size++;
}
int popFromStack(Stack *s){
assert(s->size>0);
s->size --;
return s->elements[s->size];
}
int main()
{
Stack s1;
newStack(&s1);
int i;
for(i=0; i<3; i++){
pushToStack(&s1, i);
printf("%d ", i);
}
printf("\n");
for(i=0; i<3; i++){
printf("%d ", popFromStack(&s1));
}
delStack(&s1);
getchar();
return 0;
}
The error occurs in main, on the int i; line, but if i move the line up the error goes away and the program runs flawlessly. I want to know why.
CAUSES ERROR:
newStack(&s1);
int i;
NO ERROR:
int i;
newStack(&s1);
PS: just in case it matters.. im using MS Visual Studio 2010
Visual Studio is stuck in a time loop somewhere before 1998, back when the standard mandated that all declarations should be at the beginning of a block.
This was changed in C99, and MS does say it supports the most popular features. Sadly this is not one of them.
In C you must declare all variables at the beginning of your scope. So you can't declare i after your newStack call.
In C89 declarations are made at the top of the scope and thus before any other function call.
However this restriction was removed in C99.