Put some malloc's and free's for the gets() as well as for nbBI.abs->prev and next, now I'm getting the following SIGSEGV signal
The full source code (got C&P finally working in the VM Terminal):
printBigInteger() is obviously unfinished right now, that's not the problem.
Code:
Program received signal SIGSEGV, Segmentation fault.
0x08045f2 in newBigInteger (nbS=0x804a008 "123") at test.c:44
44 nbBI.abs->prev = (Block*) malloc(sizeof(Block));
The full source code (got C&P finally working in the VM Terminal):
Code:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
typedef struct block{
struct block* prev;
int val;
struct block* next;
} Block;
typedef struct {
int sign;
Block* abs;
} BigInteger;
BigInteger newBigInteger(char*);
void printBigInteger(BigInteger);
int main(int argc, char* argv[]) {
char* nbS = (char*) malloc(sizeof(char));
BigInteger nbBI;
gets(nbS);
nbBI = newBigInteger(nbS);
printBigInteger(nbBI);
free(nbS);
free(nbBI.abs->prev);
nbBI.abs->prev = NULL;
free(nbBI.abs->next);
nbBI.abs->next = NULL;
return 0;
}
BigInteger newBigInteger(char* nbS) {
int i = 0;
int n = strlen(nbS);
BigInteger nbBI;
nbBI.sign = 0;
nbBI.abs->prev = (Block*) malloc(sizeof(Block));
nbBI.abs->prev = NULL;
nbBI.abs->val = 0;
nbBI.abs->next = (Block*) malloc(sizeof(Block));
nbBI.abs->next = NULL;
if(nbS[i] == '-') {
nbBI.sign = -1;
i++;
}
while(i < n) {
int p = 3;
while(i < n && p >= 0) {
nbBI.abs->val += atoi(&nbS[i]) * pow(10,p);
p--;
i++;
}
Block new;
nbBI.abs->prev = &new;
new.prev = NULL;
new.val = 0;
new.next = nbBI.abs;
nbBI.abs = &new;
}
return nbBI;
}
void printBigInteger(BigInteger x) {
printf("%d", x.abs->val);
}
printBigInteger() is obviously unfinished right now, that's not the problem.