I have a very simple implementation of a buffer with writing and reading index in C. Below is the .c file and then after the main().
Cant see why but I'm getting the Segmentation fault (core dumped).
The .c file is below.
#include <stdio.h>
#include <stdlib.h>
#include "contbuf.h"
typedef struct cont_buf
{
char *buf;
ln_bsize size;
int read_index;
int write_index;
int has_data;
} cont_buf;
cont_buf *create_cont_buf(ln_bsize *size)
{
cont_buf *cb;
cb->buf = malloc(sizeof(float)*(*size));
if(cb->buf == NULL){
printf("Failed to get or allocate memory\n");
exit(1);
}
cb->size = *size;
cb->read_index = 0;
cb->write_index = 0;
cb->has_data = 0;
if (!cb->buf)
return NULL;
return cb;
}
void free_cont_buf(cont_buf *cb)
{
free(&cb->buf);
}
void write_float_to_cb(cont_buf *cb, float *f)
{
if ((cb->write_index + 1) > cb->size)
{
cb->write_index = 0;
}
cb->buf[cb->write_index] = *f;
cb->write_index += 1;
if (cb->write_index > cb->has_data)
cb->has_data = cb->write_index;
}
void read_float_from_cb(cont_buf *cb)
{
float f;
f = cb->buf[cb->read_index];
printf("float number: %f\n", f);
}
And here is the main() file, just to teste the functions in the C.
There is also a .h file that I'm not sharing but it is just declaration of the functions and typedefs.
#include <stdio.h>
#include <stdlib.h>
#include "contbuf.h"
int main() {
struct cont_buf* cb;
ln_bsize* size;
*size = (ln_bsize)20;
float *f;
*f = 3.25F;
cb = create_cont_buf(size);
write_float_to_cb(cb, f);
read_float_from_cb(cb);
return 0;
}
Could someone help me to figure out why ? I also don't find a way to troubleshoot since the run doesn't even run, so I cannot tell when the code breaks.