I am getting segmentation fault and i dont know why [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am writing a vm from a tutorial and I keep getting segmentation fault. gdb is not giving me any info accept for that it is in int main() but I see nothing wrong, of course I have a bad eye for things that are wrong so if one of you smart people can help me that would be great
vm.c (I fixed the indentation)
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
typedef struct OBJECT_t {
uint8_t type;
union {
uint8_t u8;
int8_t i8;
uint32_t u32;
int32_t i32;
void *ptr;
};
} OBJECT;
typedef struct STACK_t {
int top;
int size;
OBJECT *stack;
} STACK;
typedef uint8_t* (*instruction)(uint8_t *, STACK *);
STACK stack_new(int size) {
STACK s;
s.top = 0;
s.size = size;
s.stack = (OBJECT *)malloc(sizeof(OBJECT) * size);
return s;
}
int stack_push(STACK *s, OBJECT o){
s->stack[s->top++] = o;
return s->top;
}
OBJECT stack_pop(STACK *s){
return s->stack[--(s->top)];
}
OBJECT stack_peek(STACK *s) {
return s->stack[s->top - 1];
}
void usage(){
printf("usage: vm <file>\n");
exit(1);
}
uint8_t *load_file(char *filename) {
FILE *f;
int size;
uint8_t *code = NULL;
struct stat st;
if((f = fopen(filename, "r"))) {
fstat(fileno(f), &st);
code = (uint8_t *)malloc(st.st_size);
fread((void *)code, 1, st.st_size, f);
}else {
printf("ERROR: cannot open file %s\n", filename);
usage();
}
return code;
}
uint8_t *op_nop(uint8_t *ip, STACK *s){
return ip + 1;
}
uint8_t *op_push_char(uint8_t *ip, STACK *s){
OBJECT o;
o.type = 'c';
o.u8 = *(ip + 1);
stack_push(s, o);
return ip + 2;
}
uint8_t *op_emit(uint8_t *ip, STACK *s){
OBJECT o = stack_pop(s);
putchar(o.u8);
return ip + 1;
}
int main(int argc, char **argv){
uint8_t *code;
uint8_t *ip;
STACK data;
instruction ops[256];
if(argc != 2){
usage();
}
for(int i=0;i<256;i++){
ops[i] = op_nop;
}
ops['c'] = op_push_char;
code = load_file(argv[1]);
data = stack_new(1024);
ip = code;
while(*ip != 'h'){
ip = ops[*ip](ip, &data);
}
return 0;
}
my program
hello.sp
c
c!cdclcrcocwc coclclcecHeeeeeeeeeeeeeh
this is my gdb output
Program received signal SIGSEGV, Segmentation fault.
0x00000000004014a6 in main ()

after fixing the problems discussed in the comments to the question:
when compiling AND when linking, use the parameter: -ggdb3 Which will:
result in a much larger object files and much larger executable.
will have the maximum amount of information for the gdb debugger.
Among other things, gdb will then display the line numbers.
then use the bt command to display the back trace of the stack at the time of a crash, so you know exactly how the code got to the crash.

Related

Realloc keeps returning NULL if reallocating structs [duplicate]

This question already has answers here:
Assignment of function parameter has no effect outside the function
(2 answers)
How do I modify a pointer that has been passed into a function in C?
(7 answers)
Closed 2 years ago.
Don't mind my code writing style. I specifically created this for testing purposes...
Now to the problem:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define EMB 31
#define NAME_MAX 50
struct TRIP {
char TRIP_NAME[EMB];
int TRIP_TIME;
};
struct DATE {
int day;
int month;
int year;
};
struct TRIP_INFORMATION {
char TRIP_NUMBER[EMB];
char EMBARKATION_POINT[EMB];
char SPECIFIC_DROPOFFPOINT[EMB];
char EXIT_DROPOFFPOINT[EMB];
struct DATE TRIP_DATE;
struct TRIP SPECIFIC_TRIP;
};
struct EMBARKATION_CARD{
//struct DATE TRIP_DATE;
char NAME[NAME_MAX];
int ID_NUMBER;
int PRIORITY_NUMBER;
//int TRIP_TIME;
//char EMBARKATION_POINT[EMB];
//char DROPOFFPOINT[EMB];
struct TRIP_INFORMATION TRIP_INFORMATION;
};
This is for the reference of declaration.
int BeginEmbarkationProcess(int *PASSENGER_COUNT, struct EMBARKATION_CARD * PASSENGER_TO_SAVE, int curr_day, int curr_month, int curr_year){
//struct EMBARKATION_CARD * P;
if(*PASSENGER_COUNT>1){
PASSENGER_TO_SAVE = realloc(PASSENGER_TO_SAVE, *PASSENGER_COUNT * sizeof(struct EMBARKATION_CARD));
if(PASSENGER_TO_SAVE == NULL){
puts("PASSENGER_TO_SAVE VARIABLE = HAS NOT ALLOCATED MEMORY");
return -1;
}
}
if(PASSENGER_TO_SAVE==NULL){
puts("PASSENGER TO SAVE POINTER HAS UNABLE TO ALLOCATE MEMORY");
return -1;
}
int x = 0;
for(x=0;x<*PASSENGER_COUNT;x++){
((PASSENGER_TO_SAVE+x))->ID_NUMBER = (x+1)*30;
((PASSENGER_TO_SAVE+x))->PRIORITY_NUMBER = (x+1)*17;
}
for(x=0;x<*PASSENGER_COUNT;x++){
printf("%d %d\n", (PASSENGER_TO_SAVE+x)->ID_NUMBER , (PASSENGER_TO_SAVE+x)->PRIORITY_NUMBER);
}
*PASSENGER_COUNT = *PASSENGER_COUNT + 1;
int r;
printf("ENTER -1 TO TERMINATE THIS LOOP\n");
scanf("%d", &r);
return r;
}
int main(){
//doIt();
struct EMBARKATION_CARD* E = malloc(sizeof(struct EMBARKATION_CARD));
int ct = 1;
int s = BeginEmbarkationProcess(&ct, E, 3, 3, 2020);
while(s!=-1){
s = BeginEmbarkationProcess(&ct, E, 3, 3, 2020);
}
return s;
}
Since I copy pasted this (and removed some commented out lines but eventually got tired of it), this copy pasted code might have some syntax error. Ignore those syntax error please.
The issue is that realloc WILL keep returning NULL.
This prevents me from readjusting it.
Can someone tell me what the hell is going on.
I know I may have made some errors here but I want to learn about it.
Yes I am just a student learning C language.

Segmentation fault while referencing and adding values to a structure

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

How can I dynamically fill an array of pointers to structs that I have made?

First, some background, I'm writing a file server for my systems programming class. What I have to do is write 4 client programs and a server to edit the directory of files client side. I've figured out how to actually do the transferring of the files client side, as well as how to actually get them through the socket, what I'm having a hard time doing is storing the files on the server. To try and solve this problem I've created 2 structs:
A FileSlot struct to store the file's name and contents in memory:
#ifndef __FILESLOT_H__
#define __FILESLOT_H__
#include "csapp.h"
typedef struct FILESLOT {
char *filename;
char *contents;
uint32_t length;
} FileSlot;
#endif
and a FileDrawer struct in order to actually keep track of the files on the server as I have to be able to add, remove, and list them:
#ifndef __FILEDRAWER_H__
#define __FILEDRAWER_H__
#include "csapp.h"
#include "fileslot.h"
typedef struct FILEDRAWER {
FileSlot* files[100];
uint32_t drawerSize;
} FileDrawer;
void new_fd(FileDrawer *fd);
uint32_t get_size(FileDrawer *fd);
void add_file(FileDrawer *fd, FileSlot *fs);
void rem_file(FileDrawer *fd, int index);
int search_files(FileDrawer *fd, char *name);
#endif
Basically I'm using these structs in a server loop, as the server receives the "put" command, I want the server to create a FileSlot, and stick it into the FileDrawer. In the past few days I've looked through the forums and so far learned that I need to use malloc(), which I'm a bit hazy on, but if I've learned correctly, I can create a pointer to a FileSlot allocated with malloc(), fill it with the necessary information, and then point one of the files[] elements from FileDrawer at the newly allocated FileSlot:
#include "filedrawer.h"
#include "fileslot.h"
int main(int argc, char** argv) {
FileDrawer *fdp = (FileDrawer*)malloc(sizeof(FileDrawer));
new_fd(fdp);
int i;
while (i < 5) {
uint32_t length = i;
FileSlot* fsp = (FileSlot*)malloc(sizeof(FileSlot));
fsp->filename = "file name";
fsp->contents = "contents";
fsp->length = length;
add_file(fdp, fsp);
i++;
}
for(i = 0; i < fdp->drawerSize; i++) {
printf("File Name %s \n", fdp->files[i]->filename);
}
free(fdp);
return 1;
}
However This doesn't seem to work, I get really strange output from the print loop.
ALSO: Here's the implementations for my FileDrawer functions, in case I've mistyped anything here as well
void new_fd(FileDrawer* fdp) {
FileDrawer fd;
fd = *fdp;
fd.drawerSize = 0;
*fdp = fd;
}
uint32_t get_size(FileDrawer* fdp) {
return fdp->drawerSize;
}
void add_file(FileDrawer* fdp, FileSlot *fs) {
FileDrawer fd = *fdp;
fd.files[fd.drawerSize] = fs;
fd.drawerSize++;
*fdp = fd;
}
void rem_file(FileDrawer* fdp, int index) {
FileDrawer fd;
fd = *fdp;
int i;
for(i = index; i < fd.drawerSize; i++) {
fd.files[i] = fd.files[i+1];
}
fd.drawerSize--;
*fdp = fd;
}
int search_files(FileDrawer* fdp, char *name) {
int i;
int index = -1;
for(i = 0; i < fdp->drawerSize; i++) {
if ((fdp->files[i]->filename) == name) {
index = i;
}
}
return index;
}
EDIT: I went in and fixed the mallocs, and removed the inefficiencies as suggested, so thanks for that! Now, my fdtest exits in a SEGFAULT at the first strcpy, and I can't figure out why. Any ideas?
Here's your main problem:
int i;
while (i < 5) {
You fail to initialize i before using it. Because it is uninitialized, it's value is indeterminate and attempting to read it causes undefined behavior.
Initialize i to 0 and it will behave properly.
int i = 0;
while (i < 5) {
Besides this, you have some inefficiencies in your code.
In new_fd and add_file, you copy the contents of a dereferenced pointer into a local variable, modify the local, then copy the contents back. That's unnecessary work. Just work directly on the passed-in pointer.
void new_fd(FileDrawer* fdp) {
fdp->drawerSize = 0;
}
void add_file(FileDrawer* fdp, FileSlot *fs) {
fdp->files[fdp->drawerSize] = fs;
fdp->drawerSize++;
}
You can perform similar changes in rem_file.
Also, don't cast the return value of malloc, as it can hide subtle bugs.

trying to my allocate memory function in c? [closed]

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;
}

C program: Segmentation Fault [closed]

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;

Resources