I am working on making a simple perception model in C and I had decided that I wanted to have some sort of abstraction using opaque pointers. Code bellow could give more clues to the problem
perceptron.h
#ifndef __PERCEPTRON_H__
#define __PERCEPTRON_H__
typedef struct _Perceptron _perceptron;
typedef struct{
//public
float * input;
float * weigths;
int size;
//private
void * m_perceptron;
}Perceptron;
Perceptron * InitPerceptron();
void FreePerceptron(Perceptron * instance);
void FeedForward(float input[],float weights[],int size,Perceptron * perceptron);
#endif
and this is my perception.c
typedef struct _Perceptron{
float * input;
int size;
}_perceptron;
static void _FeedForward(float input[],float weights[],int size,_perceptron * p){
if(p->input == NULL)
p->input = (float *)calloc(size,sizeof(float));
for(int i = 0;i < size;i++)
p->input[i] = input[i] * weights[i];
for(int i = 0;i < size;i++)
printf("%f ",p->input[i]);
}
Perceptron * InitPerceptron(){
Perceptron * instance = (Perceptron *)malloc(sizeof(Perceptron));
instance ->m_perceptron = (_perceptron *)malloc(sizeof(_perceptron));
return instance;
}
void FeedForward(float input[],float weights[],int size,Perceptron * perceptron) {
if(perceptron->input == NULL)
perceptron->input = (float *)malloc(size*sizeof(float));
if(perceptron->weigths == NULL)
perceptron->weigths = (float *)malloc(size*sizeof(float));
for(int i = 0;i < size;i++){
perceptron->input[i] = input[i];
perceptron->weigths[i] = weights[i];
}
perceptron->size = size;
_FeedForward(perceptron->input,perceptron->weigths,perceptron->size,perceptron->m_perceptron);
}
void FreePerceptron(Perceptron * instance){
free(instance->m_perceptron);
free(instance);
}
and this is my main.c
float input[] = {1,2,3};
float weights[] = {1,1,1};
Perceptron * perceptron = InitPerceptron();
FeedForward(input,weights,3,perceptron);
FreePerceptron(perceptron);
return 0;
(gdb) r
Starting program: E:\repos\NeuralNetwork\bin\neuralnetwork.exe
[New Thread 14564.0x49c4]
[New Thread 14564.0x3a44]
Thread 1 received signal SIGSEGV, Segmentation fault.
0x00000000004017b4 in FeedForward ()
(gdb)
This is the error I am getting
My initial guess is that maybe I am accessing pointers perception and _perceptron as NULL pointers, so I tried removing the FeedForward function and it seems to work just fine. My next guess is that the inputs probably are given in a wrong way, but that does not seem likely.What could be the cause for the segmentation fault. Could it be in the main function itself our is it something related to the use of malloc to the float pointers or is the use of my opaque pointers wrong ?
The values stored here are uninitialized at the moment of comparison:
if(perceptron->input == NULL)
and
if(perceptron->weigths == NULL)
and
if(p->input == NULL)
Which means that there may be no memory allocated for these pointers. Set these explicitly toNULL to solve the problem.
Side note: It is "weights", not "weigths".
Related
I am getting segmentation fault whenever I do this. I wonder if there is a way for me to assign a value to the struct without getting SegFault?
typedef struct _chunk
{
int lo; // lower bound
int hi; // higher bound
} chunk;
chunk_stack = (chunk **)malloc(10 * 10 * sizeof(chunk **));
for (i = 0; i < chunk_per_thread; i++)
{
chunk_stack[myid][i].lo = 0;
chunk_stack[myid][i].hi = 1;
}
Suppose you need to allocate a 2D array of size r * c.You need to first allocate memory for the double pointer which you did but have an error in it i.e., one extra * inside malloc function.
chunk **chunk_stack = (chunk **)malloc(r * sizeof(chunk *));
Then you need to allocate memory for each of the rows separately.
for(int i = 0; i < r; i++){
chunk_stack[i] = (chunk*)malloc(c * sizeof(chunk));
}
I am a beginner with C and currently struggling with using structs in functions. Even tho I give my functions the pointer to my struct and use that to change their values it seems like my functions are unable to change the value of the pointer themselves
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
typedef struct Vector
{
int n;
double *entry;
}Vector;
//defining the struct vector with n for its length and entry as a pointer which will become an array for its values
Vector *newVector(int n)
{
int i = 0;
Vector *X = NULL;
assert(n > 0);
X = malloc(sizeof(Vector));
assert(X != NULL);
X->n = n;
X->entry = malloc(n+1*sizeof(double));
assert(X->entry != NULL);
X->entry[0] = 0;
for (i=1; i<n+1; ++i) {
scanf("%lf",&X->entry[i]);
}
return X;
}
//making a new vector struct from the size given and returning its pointer (the array is made so it goes from 1-n instead of 0-(n-1)
void delVector(Vector *X)
{
assert(X != NULL);
assert(X->entry != NULL);
free(X->entry);
free(X);
X = NULL;
}
int getVectorLength (Vector *X)
{
assert(X != NULL);
return X->n;
}
void setVectorLength(Vector *X, int k)
{
assert(X != NULL);
assert(k>0);
delVector(X);
printf("so far.\n");
X = newVector(k);
} //deleting the vector and then replacing it with the new sized vector
double getVectorEntry (Vector *X, int h)
{
return X->entry[h];
}
void setVectorEntry (Vector *X, int h)
{
printf("Value %d.\n",h);
scanf("%lf",&X->entry[h]);
}
main()
{
Vector *h = NULL;
h = newVector(3);
printf("%f\n",h->entry[1]);
printf("%f\n",getVectorEntry(h,1));
setVectorEntry(h,1);
printf("%f\n",getVectorEntry(h,1));
printf("%d\n",getVectorLength(h));
setVectorLength(h,6);
printf("%f\n",getVectorEntry(h,6));
setVectorEntry(h,6);
printf("so far.\n");
printf("%f\n",getVectorEntry(h,6));
}
Running the code would make it crash once it reaches delVector. If I were to comment the delVector out it would crash at X = newVector(k); for a reason I also cannot find out (it starts the function newVector, but crashes before I can input). So what is causing the errors?
Thanks a lot in advance!
Let's just focus on the setVectorLength function
void setVectorLength(Vector *X, int k)
{
assert(X != NULL);
assert(k>0);
delVector(X);
printf("so far.\n");
X = newVector(k);
}
Here, Vector *X is a local variable that only exists in this function. It points to some location in memory, but using it you can't modify the original pointer. So there are two ways around it.
1. You don't delete and recreate the vector. Instead do something like this
void setVectorLength(Vector *X, int k)
{
X->entry = realloc(X->entry, k*sizeof(double)); // frees X->entry and allocates it to a new heap array
X->k = k;
}
2. Use a pointer pointer. Do note, that this will be slower and is unnecessary. Go for the 1 solution.
void setVectorLength(Vector **X, int k)
{
assert(*X != NULL);
assert(k>0);
delVector(*X);
printf("so far.\n");
*X = newVector(k);
}
The variable Vector **X points to the original variable, so you can modify it.
Problem seem to be in function
Vector *newVector(int n)
{
int i = 0;
Vector *X = NULL;
assert(n > 0);
X = malloc(sizeof(Vector));
assert(X != NULL);
X->n = n;
X->entry = malloc(n+1*sizeof(double));
assert(X->entry != NULL);
X->entry[0] = 0;
for (i=1; i<n+1; ++i) {
scanf("%lf",&X->entry[i]);
}
return X;
}
In above statement, you are allocating X->entry with n + sizeof(double) but as per your requirement you should allocated (n + 1) * sizeof(double)
You should allocate memory for X->entry as
X->entry = malloc((n + 1) * sizeof(double));
Your allocation is wrong, you have to group the n and the 1 like you do it on paper so. Not that the expression you have n + 1 * sizeof(double) means the same as n + sizeof(double).
X->entry = malloc((n + 1) * sizeof(*X->entry));
would be the right way!
As it was, your code invokes undefined behavior and once possible consequence is for the program to crash. Most likely because trying to access memory out of it's memory space so a segmentation fault occurs.
void setVectorLength(Vector *X, int k)
{
assert(X != NULL);
assert(k>0);
delVector(X);
printf("so far.\n");
X = newVector(k);
}
In this function, X is a copy of the pointer variable the caller passes in. It contains a copy of the address. Modifying a function parameter doesn't change the caller's value. Just as doing k = 0 would have no effect on the caller, reassigning X is a local change that is invisible to the caller.
If you want the caller to see the result of newVector(k), you have a couple options. You could change setVectorLength() to work like newVector() and return the new pointer.
Vector *setVectorLength(Vector *X, int k) {
...
printf("so far.\n");
return newVector(k);
}
int main() {
...
h = setVectorLength(h, 6);
}
Or you could add another layer of indirection—make X a pointer to a pointer. That would require the caller to pass the address of the variable they want changed. Instead of passing h you'd pass &h.
void setVectorLength(Vector *X, int k) {
...
printf("so far.\n");
*X = newVector(k);
}
int main() {
...
setVectorLength(&h, 6);
}
By the way, the way you've written setVectorLength(), it will destroy any existing data in the vector. You may want to copy the data from the old vector to the new one. (Or, as #pi_pi3 suggests, modify the vector in place instead of destroying it and creating a new one.)
I get the Error run-time check failure #3, and i have to initialize P and i know why but not how to do it.
Points is supposed to be a variable 2D array like float* points[3] for testing purposes its constant for now.
CVAPI(CvPOSITObject*) lvCreatePOSITObject( float points[5][3], int point_count )
{
CvPoint3D32f* P; //array of structs with int x,y,z
for(int i = 0; i< point_count; i++)
{
P[i].x = points[i][0];
P[i].y = points[i][1];
P[i].z = points[i][2];
}
return cvCreatePOSITObject(P,point_count);
}
I don't know much about OpenCV, but I think you should allocate some memory to store the data.
#include <stdlib.h> // add this to the head of the file to use malloc
CVAPI(CvPOSITObject*) lvCreatePOSITObject( float points[5][3], int point_count )
{
CvPoint3D32f* P; //array of structs with int x,y,z
P = malloc(sizeof(CvPoint3D32f) * point_count); // allocate some memory
for(int i = 0; i< point_count; i++)
{
P[i].x = points[i][0];
P[i].y = points[i][1];
P[i].z = points[i][2];
}
return cvCreatePOSITObject(P,point_count);
}
This code may be bad because this may not free the allocated buffer.
I'm working on a C implementation for Conway's game of life, I have been asked to use the following header:
#ifndef game_of_life_h
#define game_of_life_h
#include <stdio.h>
#include <stdlib.h>
// a structure containing a square board for the game and its size
typedef struct gol{
int **board;
size_t size;
} gol;
// dynamically creates a struct gol of size 20 and returns a pointer to it
gol* create_default_gol();
// creates dynamically a struct gol of a specified size and returns a pointer to it.
gol* create_gol(size_t size);
// destroy gol structures
void destroy_gol(gol* g);
// the board of 'g' is set to 'b'. You do not need to check if 'b' has a proper size and values
void set_pattern(gol* g, int** b);
// using rules of the game of life, the function sets next pattern to the g->board
void next_pattern(gol* g);
/* returns sum of all the neighbours of the cell g->board[i][j]. The function is an auxiliary
function and should be used in the following function. */
int neighbour_sum(gol* g, int i, int j);
// prints the current pattern of the g-board on the screen
void print(gol* g);
#endif
I have added the comments to help out with an explanation of what each bit is.
gol.board is a 2-level integer array, containing x and y coordinates, ie board[x][y], each coordinate can either be a 1 (alive) or 0 (dead).
This was all a bit of background information, I'm trying to write my first function create_default_gol() that will return a pointer to a gol instance, with a 20x20 board.
I then attempt to go through each coordinate through the 20x20 board and set it to 0, I am getting a Segmentation fault (core dumped) when running this program.
The below code is my c file containing the core code, and the main() function:
#include "game_of_life.h"
int main()
{
// Create a 20x20 game
gol* g_temp = create_default_gol();
int x,y;
for (x = 0; x < 20; x++)
{
for (y = 0; y < 20; y++)
{
g_temp->board[x][y] = 0;
}
}
free(g_temp);
}
// return a pointer to a 20x20 game of life
gol* create_default_gol()
{
gol* g_rtn = malloc(sizeof(*g_rtn) + (sizeof(int) * 20 * 20));
return g_rtn;
}
This is the first feature I'd like to implement, being able to generate a 20x20 board with 0's (dead) state for every coordinate.
Please feel free to criticise my code, I'm looking to determine why I'm getting the segmentation fault, and if I'm allocating memory properly in the create_default_gol() function.
Thanks!
The type int **board; means that board must contain an array of pointers, each of which points to the start of each row. Your existing allocation omits this, and just allocates *g_rtn plus the ints in the board.
The canonical way to allocate your board, supposing that you must stick to the type int **board;, is:
gol* g_rtn = malloc(sizeof *g_rtn);
g_rtn->size = size;
g_rtn->board = malloc(size * sizeof *g_rtn->board);
for (int i = 0; i < size; ++i)
g_rtn->board[i] = malloc(size * sizeof **g_rtn->board);
This code involves a lot of small malloc chunks. You could condense the board rows and columns into a single allocation, but then you also need to set up pointers to the start of each row, because board must be an array of pointers to int.
Another issue with this approach is alignment. It's guaranteed that a malloc result is aligned for any type; however it is possible that int has stricter alignment requirements than int *. My following code assumes that it doesn't; if you want to be portable then you could add in some compile-time checks (or run it and see if it aborts!).
The amount of memory required is the sum of the last two mallocs:
g_rtn->board = malloc( size * size * sizeof **g_rtn->board
+ size * sizeof *g_rtn->board );
Then the first row will start after the end of the row-pointers (a cast is necessary because we are converting int ** to int *, and using void * means we don't have to repeat the word int):
g_rtn->board[0] = (void *) (g_rtn->board + size);
And the other rows each have size ints in them:
for (int i = 1; i < size; ++i)
g_rtn->board[i] = g_rtn->board[i-1] + size;
Note that this is a whole lot more complicated than just using a 1-D array and doing arithmetic for the offsets, but it was stipulated that you must have two levels of indirection to access the board.
Also this is more complicated than the "canonical" version. In this version we are trading code complexity for the benefit of having a reduced number of mallocs. If your program typically only allocates one board, or a small number of boards, then perhaps this trade-off is not worth it and the canonical version would give you fewer headaches.
Finally - it would be possible to allocate both *g_rtn and the board in the single malloc, as you attempted to do in your question. However my advice (based on experience) is that it is simpler to keep the board separate. It makes your code clearer, and your object easier to use and make changes to, if the board is a separate allocation to the game object.
create_default_gol() misses to initialise board, so applying the [] operator to it (in main() ) the program accesses "invaid" memory and with ethis provokes undefined behaviour.
Although enough memory is allocated, the code still needs to make board point to the memory by doing
gol->board = ((char*) gol) + sizeof(*gol);
Update
As pointed out by Matt McNabb's comment board points to an array of pointers to int, so initialisation is more complicate:
gol * g_rtn = malloc(sizeof(*g_rtn) + 20 * sizeof(*gol->board));
g_rtn->board = ((char*) gol) + sizeof(*gol);
for (size_t i = 0; i<20; ++i)
{
g_rtn->board[i] = malloc(20 * sizeof(*g_rtn->board[i])
}
Also the code misses to set gol's member size. From what you tell us it is not clear whether it shall hold the nuber of bytes, rows/columns or fields.
Also^2 coding "magic numbers" like 20 is bad habit.
Also^3 create_default_gol does not specify any parameters, which explictily allows any numberm and not none as you might perhaps have expected.
All in all I'd code create_default_gol() like this:
gol * create_default_gol(const size_t rows, const size_t columns)
{
size_t size_rows = rows * sizeof(*g_rtn->board));
size_t size_column = columns * sizeof(**g_rtn->board));
gol * g_rtn = malloc(sizeof(*g_rtn) + size_rows);
g_rtn->board = ((char*) gol) + sizeof(*gol);
if (NULL ! = g_rtn)
{
for (size_t i = 0; i<columns; ++i)
{
g_rtn->board[i] = malloc(size_columns); /* TODO: Add error checking here. */
}
g_rtn->size = size_rows * size_columns; /* Or what ever this attribute is meant for. */
}
return g_rtn;
}
gol* create_default_gol()
{
int **a,i;
a = (int**)malloc(20 * sizeof(int *));
for (i = 0; i < 20; i++)
a[i] = (int*)malloc(20 * sizeof(int));
gol* g_rtn = (gol*)malloc(sizeof(*g_rtn));
g_rtn->board = a;
return g_rtn;
}
int main()
{
// Create a 20x20 game
gol* g_temp = create_default_gol();
int x,y;
for (x = 0; x < 20; x++)
{
for (y = 0; y < 20; y++)
{
g_temp->board[x][y] = 10;
}
}
for(x=0;x<20;x++)
free(g_temp->board[x]);
free(g_temp->board);
free(g_temp);
}
main (void)
{
gol* gameOfLife;
gameOfLife = create_default_gol();
free(gameOfLife);
}
gol* create_default_gol()
{
int size = 20;
gol* g_rtn = malloc(sizeof *g_rtn);
g_rtn = malloc(sizeof g_rtn);
g_rtn->size = size;
g_rtn->board = malloc(size * sizeof *g_rtn->board);
int i, b;
for (i = 0; i < size; ++i){
g_rtn->board[i] = malloc(sizeof (int) * size);
for(b=0;b<size;b++){
g_rtn->board[i][b] = 0;
}
}
return g_rtn;
}
Alternatively, since you also need to add a create_gol(size_t new_size) of custom size, you could also write it as the following.
main (void)
{
gol* gameOfLife;
gameOfLife = create_default_gol();
free(gameOfLife);
}
gol* create_default_gol()
{
size_t size = 20;
return create_gol(size);
}
gol* create_gol(size_t new_size)
{
gol* g_rtn = malloc(sizeof *g_rtn);
g_rtn = malloc(sizeof g_rtn);
g_rtn->size = new_size;
g_rtn->board = malloc(size * sizeof *g_rtn->board);
int i, b;
for (i = 0; i < size; ++i){
g_rtn->board[i] = malloc(sizeof (int) * size);
for(b=0;b<size;b++){
g_rtn->board[i][b] = 0;
}
}
return g_rtn;
}
Doing this just minimizes the amount of code needed.
I'm new to multithreading had my first lesson yesterday. So I've wrote a program to get the average of 4 big arrays , each array is a thread and the main waits for all the threads and gives the average of the 4 arrays. This is possible because each thread gives the average of one array. The array is just a headerfile with a float array.
It compiles but gives me a segmentation error and I don't see why.
#include "gemiddelde.h"
#include <stdlib.h>
#include <stdio.h>
float *gemiddelde(void *arg)
{
float *a;
int i;
a = (float *)arg;
float * som;
for( i = 0; i < 100000; i++)
*som += a[i];
*som = *som / 100000;
return som;
}
int main()
{
pthread_t t1,t2,t3,t4;
float * som1, * som2, * som3, * som4, *result;
pthread_create(&t1,NULL,gemiddelde,a1);
pthread_create(&t2,NULL,gemiddelde,a2);
pthread_create(&t3,NULL,gemiddelde,a3);
pthread_create(&t4,NULL,gemiddelde,a4);
pthread_join(t1,som1);
pthread_join(t2,som2);
pthread_join(t3,som3);
pthread_join(t4,som4);
usleep(1);
*result = *som1 + *som2 + *som3 + *som4;
printf("Gemiddelde is: %f ", *result);
return 0;
}
Can someone help me?
Kind regards,
In
*result = *som1 + *som2 + *som3 + *som4;
result is used unitialized. Make it a plain float instead of a pointer.
From your current code, segfault occurs because som* aren't initialized -- they are dangling pointers.
Your code is very problematic, because the thread code requires memory to store the result, and as it stands your code is plain wrong because it doesn't have any memory and just dereferences a dangling pointer. But even allocating memory inside the thread is not a great idea, because it's not clear who is responsible for it and who will clean it up. So it's much better to allocate all your required memory in the main function. First some boiler plate to set up the thread argument data:
typedef struct thread_arg_type_
{
float * data;
size_t len;
float retval;
} thread_arg_type;
thread_arg_type * create_thread_arg(size_t n)
{
thread_arg_type * result = malloc(sizeof(thread_arg_type));
if (!result) return NULL;
float * const p = malloc(n * sizeof(float));
if (!p)
{
free(result);
return NULL;
}
result->len = n;
result->data = p;
return result;
}
void free_thread_arg(thred_arg_type * r)
{
if (r) free(r->data);
free(r);
}
Now here's how we use it:
int main()
{
thread_arg_type * arg;
pthread_t t;
arg = create_thread_arg(array1_size);
pthread_create(&t, NULL, getmiddle, arg);
// ...
pthread_join(t, NULL);
printf("The result is: %f.\n", arg->retval);
free_thread_arg(arg);
}
And finally we must adapt getmiddle:
void * getmiddle(thread_arg_t * arg)
{
arg->retval = 0;
for(unsigned int i = 0; i != arg->len; ++i)
arg->retval += arg->data[i];
arg->retval /= arg->len;
return NULL;
}