Segmentation Fault in Initializing a structure - c

I'm aiming to implement an algorithm to check if a graph is topologic. But well, that's not the issue here. I'm getting a core dump when trying to initialize my graph structure with the given data.
Program received signal SIGSEGV, Segmentation fault.
0x00000000004009a3 in initGraph (numberNode=15, numberArc=17, g=0x1) at src/topologicGraphOp.c:45
45 g->numberNode = numberNode;
I'm really confused because the issue seems so obvious and yet, I cannot find it after various tries so I'm hoping that someone will find that dumb error like "bah, it's obvious" because well... I'm out of luck...
Here is the structure :
typedef struct {
int numberNode;
int numberArc;
int *distances;
int *predecessors;
float **matrix;
queue *successors;
char *graphTitle;
char **nodeDescription;
int *time;
} graph;
And the function where the core dump seem to appear:
void initGraph(int numberNode, int numberArc, graph *g) {
int i, j;
g->numberNode = numberNode;
g->numberArc = numberArc;
g->nodeDescription = malloc(numberNode * sizeof (char));
g->matrix = (float **) calloc(g->numberNode, sizeof (float*));
for (i = 0; i < g->numberNode; i++) {
g->matrix[i] = (float *) calloc(g->numberNode, sizeof (float));
g->nodeDescription[i] = malloc(sizeof (char));
}
}
My main function just calls the initializing function.
Thanks a lot!
edit: The solution in the comment :)
I forgot to malloc my graph pointer before using it in the function.

Calling from main() must be like this:
graph g;
initGraph(1, 1, &g);
or like this:
graph *g = malloc( sizeof(graph) );
initGraph(1, 1, g);
EDIT:
In the comments there is a multivoted question about how I explained that there is an error in the code that is not shown in the OP query.
Lets see beginning of the function:
void initGraph(int numberNode, int numberArc, graph *g) {
int i, j;
g->numberNode = numberNode;
}
And the error:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004009a3 in initGraph (numberNode=15, numberArc=17, g=0x1) at src/topologicGraphOp.c:45
45 g->numberNode = numberNode;
The error mention line 45 and I was asked question in comment about how we can know where the line 45. However, I immediately removed question because near the line number error show line content, so we can find that line in mentioned code.
Code at line 45 is enough simple and may cause error only when pointer g is referred to wrong memory.
The pointer g is not modified by this function before use. This function supposes the valid memory pointed by function param g.
Therefore, function is called with wrong pointer for param g. So I just suggested valid and typical approach to proper initialize variable and call such function with such param.

A segmentation fault virtually always means you are messing up a pointer in some way. Either during allocation, or during dereference (for reading or writing, that's the same thing here). You might also have changed the address it points to, for example by forgetting to dereference it on assignment (similar to *g = ...; becomes g = ...;); that particular mistake would be less likely with structures, but you never know...
Consequently, when you get a segmentation fault, always double-check all pointers involved in the problematic statement. In this case, g is the only pointer involved (both the parameter and the field numberNode are non-pointer variables), so g is the suspect part.
You don't show us how you call the initialization function, but in this case the code is simple enough that the cause should be obvious once you look at where the g parameter to initGraph() is coming from, and what its value (and address) is on entry to initGraph(). Is g allocated at all? Does g point to a sufficiently large block of memory to hold the entire structure? Has any relevant field (e.g. in the case of a pointer to a structure that itself contains pointers) been initialized, and is the value reasonable immediately before the problematic statement?
If you are still uncertain, look at the address and value of that pointer, either through the debugger or by adding something like printf("&g=(%p)",g); to the top of initGraph(). Invalid pointers have a tendency to stand out quite well from the noise of actual memory addresses.

Related

double free or corruption (!prev) but for sure no double free()

I am getting a double free or corruption (!prev) but I do not know why. So far I understand what it will tell me. At least I am not doing a double free but it fails for sure on the free() command.
Ok, some code. I have a structure defined as follows:
#define OWMINDEV 2
struct owdevice_struct {
char name[30];
float value;
};
struct ow_struct {
int countdev;
struct owdevice_struct *owdevice;
};
struct ow_struct ow;
Initially I assign values and use the *owdevice as array and I can access and assign values:
ow.countdev = OWMINDEV;
ow.owdevice = malloc( OWMINDEV * sizeof(struct owdevice_struct));
strcpy(ow.owdevice[0].name,"t_abl_i");
ow.owdevice[0].value = 3.5;
strcpy(ow.owdevice[1].name,"t_out");
ow.owdevice[1].value = 1.5;
I can easily access and read all these values. Fine so far. Now I have a routine which does some sort of re-assigning these variables with a different count (dynamic array). So my idea is to free up the memory which is pointed to by ow.owdevice and do an alloc again with the new number of devices.
m = 5;
free(ow.owdevice);
ow.owdevice = NULL;
ow.owdevice = calloc( m, sizeof(struct owdevice_struct));
But as soon as the program goes to free() I am getting the error. And no, there are really no other free() calls anywhere in the code regarding the ow variable. As it can not be a double free it appears to be a corruption, right? But why?
Interestingly, the first call of the above code (with a countdev of 3 freeing and allocating to a countdev of 20) works without any issues. Just the second call then causes the error.
Any ideas here, guys?
Thanks in advance!
/KNEBB
Ok, I found the issue.
I had a function which rearranged the items in the above array. Originally I configured three items to be fixed and skipped this items when rearranging.
Further coding I added another two fixed devices but I forgot to skip these, too. So my code included these in rearrangement and wrote to [20] and [21] instead of [19] max.
It wrote after the allocated memory which caused the error when trying to free().
Thanks for all your hints!

Weird behaviour with variable length arrays in struct in C

I came across a concept which some people call a "Struct Hack" where we can declare a pointer variable inside a struct, like this:
struct myStruct{
int data;
int *array;
};
and later on when we allocate memory for a struct myStruct using malloc in our main() function, we can simultaneously allocate memory for our int *array pointer in same step, like this:
struct myStruct *p = malloc(sizeof(struct myStruct) + 100 * sizeof(int));
p->array = p+1;
instead of
struct myStruct *p = malloc(sizeof(struct myStruct));
p->array = malloc(100 * sizeof(int));
assuming we want an array of size 100.
The first option is said to be better since we would get a continuous chunk of memory and we can free that whole chunk with one call to free() versus 2 calls in the latter case.
Experimenting, I wrote this:
#include<stdio.h>
#include<stdlib.h>
struct myStruct{
int i;
int *array;
};
int main(){
/* I ask for only 40 more bytes (10 * sizeof(int)) */
struct myStruct *p = malloc(sizeof(struct myStruct) + 10 * sizeof(int));
p->array = p+1;
/* I assign values way beyond the initial allocation*/
for (int i = 0; i < 804; i++){
p->array[i] = i;
}
/* printing*/
for (int i = 0; i < 804; i++){
printf("%d\n",p->array[i]);
}
return 0;
}
I am able to execute it without problems, without any segmentation faults. Looks weird to me.
I also came to know that C99 has a provision which says that instead of declaring an int *array inside a struct, we can do int array[] and I did this, using malloc() only for the struct, like
struct myStruct *p = malloc(sizeof(struct myStruct));
and initialising array[] like this
p->array[10] = 0; /* I hope this sets the array size to 10
and also initialises array entries to 0 */
But then again this weirdness where I am able to access and assign array indices beyond the array size and also print the entries:
for(int i = 0; i < 296; i++){ // first loop
p->array[i] = i;
}
for(int i = 0; i < 296; i++){ // second loop
printf("%d\n",p->array[i]);
}
After printing p->array[i] till i = 296 it gives me a segmentation fault, but clearly it had no problems assigning beyond i = 9.
(If I increment 'i' till 300 in the first for loop above, I immediately get a segmentation fault and the program doesn't print any values.)
Any clues about what's happening? Is it undefined behaviour or what?
EDIT: When I compiled the first snippet with the command
cc -Wall -g -std=c11 -O struct3.c -o struct3
I got this warning:
warning: incompatible pointer types assigning to 'int *' from
'struct str *' [-Wincompatible-pointer-types]
p->array = p+1;
Yes, what you see here is an example of undefined behavior.
Writing beyond the end of allocated array (aka buffer overflow) is a good example of undefined behavior: it will often appear to "work normally", while other times it will crash (e.g. "Segmentation fault").
A low-level explanation: there are control structures in memory that are situated some distance from your allocated objects. If your program does a big buffer overflow, there is more chance it will damage these control structures, while for more modest overflows it will damage some unused data (e.g. padding). In any case, however, buffer overflows invoke undefined behavior.
The "struct hack" in your first form also invokes undefined behavior (as indicated by the warning), but of a special kind - it's almost guaranteed that it would always work normally, in most compilers. However, it's still undefined behavior, so not recommended to use. In order to sanction its use, the C committee invented this "flexible array member" syntax (your second syntax), which is guaranteed to work.
Just to make it clear - assignment to an element of an array never allocates space for that element (not in C, at least). In C, when assigning to an element, it should already be allocated, even if the array is "flexible". Your code should know how much to allocate when it allocates memory. If you don't know how much to allocate, use one of the following techniques:
Allocate an upper bound:
struct myStruct{
int data;
int array[100]; // you will never need more than 100 numbers
};
Use realloc
Use a linked list (or any other sophisticated data structure)
What you describe as a "Struct Hack" is indeed a hack. It is not worth IMO.
p->array = p+1;
will give you problems on many compilers which will demand explicit conversion:
p->array = (int *) (p+1);
I am able to execute it without problems, without any segmentation faults. Looks weird to me.
It is undefined behaviour. You are accessing memory on the heap and many compilers and operating system will not prevent you to do so. But it extremely bad practice to use it.

c free pointer to structure

I'm writing in plain C and I have an issue about how to free a pointer to a structure.
I have a structure declared in the following way
typedef struct _RealMatrix {
uint nRows;
uint nCols;
real **matrix;
} RealMatrix;
Now, every time I need it I use the following code to allocate it
RealMatrix *realMatrixAlloc(uint n, uint m) {
loop_var(i);
RealMatrix *matrix;
matrix = malloc(sizeof(RealMatrix));
errcheck(matrix, "Unable to create real matrix structure.");
matrix->nRows = n;
matrix->nCols = m;
matrix->matrix = malloc(n*sizeof(real *));
matrix->matrix[0] = malloc(n*m*sizeof(real));
errcheck(matrix->matrix && matrix->matrix[0], "Unable to get requested memory for real matrix of dimensions: (%u, %u).", n, m);
f_i(i < n) matrix->matrix[i] = matrix->matrix[0] + i*m;
return matrix;
}
where errcheck() is a allocation checking macro. Everything works just fine until I try to deallocate it calling
freeRealMatrix(&myRealMatrix);
which will
free((*ma)->matrix[0]),
free((*ma)->matrix)
free(*ma).
*ma = NULL;
with suitable checks to avoid following any NULL pointer. Here "ma" is the pointer TO THE POINTER to the structure: the function declaration reads
void freeRealMatrix(RealMatrix **ma);
However when this function returns I find out that "myRealMatrix" is still addressing an existing structure, which was not deallocated as I expected by free(*ma). On the other hand the array (*ma)->matrix has been successfully deallocated.
Any ideas about what am I doing wrong? This is driving me crazy...
Thanks in advance!
UPDATE:
I copied the code and executed in a brand new program... It works precisely as expected. I noticed that the address contained in "myRealMatrix" isn't the same as the address pointed by *ma. Well... Sort of: it seems truncated! Instead of being 0x106a50 it is just 0x106a and no more. The last two hex digits are missing every time!
After a free, your pointer continues to contain the address of the freed location. You can not continue addressing this location though. It can be used for something else.
You may want to explicitly set it to NULL after the third free statement:
*ma = NULL;

Malloc call crashing, but works elsewhere

I wonder if anyone might have any insight on this...
My program is crashing on this call:
void subtract(data* array,data* inverse,int a, int b, int q, int n)
{
data* arraytomultiply;
arraytomultiply = (data *)malloc(sizeof(data*) * n);
Where data just holds an int (it's for convenience when switching types later)
typedef struct {
int value;
}data;
I've tried lots of messing around with changing the pointers here as I'm not confident on them at all, but to no avail.
The strange thing is, much earlier in the program this same call works, I assign values to it and can print them out and everything..:
data* array;
array = (data*)malloc(sizeof(data*) * m * n); // m * n entries
One thing that might be of use (though I have no idea why) is that when it works earlier it's during a void function, whereas when it crashes it's in a function called from within an algorithm. but I don't see how this could affect it at all, given what I'm trying to do isn't using any of the arguments etc...
Any ideas?
Shouldn't that be sizeof(data) instead of sizeof(data*) since you're allocating space for data structures?
You are allocating m * n elements of data * and not data. If you want array of pointers to data then what you are doing in malloc() is correct but that should be assigned to data **
array = (data*)malloc(sizeof(data*) * m * n); // m * n entries
It should be
array = (data*)malloc(sizeof(data) * m * n); // m * n entries
and, you should always check the return value of malloc() to find whether it fails or succeeds!
if ((array = (data*)malloc(sizeof(data) * m * n)) == NULL) {
printf("unable to allocate memory");
return; // you can return your error code here!
}
Your program has all the reason to crash. But when you said, it worked earlier but crashed later made be to do some experiments. I tried your code snippet and found it working for me. I tried many a times but it never crashed. I got puzzled and I posted a question to find out why?! - It is available here Are "malloc(sizeof(struct a *))" and "malloc(sizeof(struct a))" the same?
+1 to your question!
You all are right, but anyhow I wonder why this crashes.
I wonder because the size of data (as defined above) is expected to be less or equal to the size of data*.
When malloc crashes, it is usually because you have messed up the structures it uses to track memory on the heap somewhere else. Is your program multi-threaded? Try running it with helgrind or drd (both valgrind tools). These can help you track down race conditions, unprotected data accesses, or other threading issues.

How to realloc an array inside a function with no lost data? (in C )

I have a dynamic array of structures, so I thought I could store the information about the array in the first structure.
So one attribute will represent the amount of memory allocated for the array and another one representing number of the structures actually stored in the array.
The trouble is, that when I put it inside a function that fills it with these structures and tries to allocate more memory if needed, the original array gets somehow distorted.
Can someone explain why is this and how to get past it?
Here is my code
#define INIT 3
typedef struct point{
int x;
int y;
int c;
int d;
}Point;
Point empty(){
Point p;
p.x=1;
p.y=10;
p.c=100;
p.d=1000; //if you put different values it will act differently - weird
return p;
}
void printArray(Point * r){
int i;
int total = r[0].y+1;
for(i=0;i<total;i++){
printf("%2d | P [%2d,%2d][%4d,%4d]\n",i,r[i].x,r[i].y,r[i].c,r[i].d);
}
}
void reallocFunction(Point * r){
r=(Point *) realloc(r,r[0].x*2*sizeof(Point));
r[0].x*=2;
}
void enter(Point* r,int c){
int i;
for(i=1;i<c;i++){
r[r[0].y+1]=empty();
r[0].y++;
if( (r[0].y+2) >= r[0].x ){ /*when the amount of Points is near
*the end of allocated memory.
reallocate the array*/
reallocFunction(r);
}
}
}
int main(int argc, char** argv) {
Point * r=(Point *) malloc ( sizeof ( Point ) * INIT );
r[0]=empty();
r[0].x=INIT; /*so here I store for how many "Points" is there memory
//in r[0].y theres how many Points there are.*/
enter(r,5);
printArray(r);
return (0);
}
Your code does not look clean to me for other reasons, but...
void reallocFunction(Point * r){
r=(Point *) realloc(r,r[0].x*2*sizeof(Point));
r[0].x*=2;
r[0].y++;
}
The problem here is that r in this function is the parameter, hence any modifications to it are lost when the function returns. You need some way to change the caller's version of r. I suggest:
Point * // Note new return type...
reallocFunction(Point * r){
r=(Point *) realloc(r,r[0].x*2*sizeof(Point));
r[0].x*=2;
r[0].y++;
return r; // Note: now we return r back to the caller..
}
Then later:
r = reallocFunction(r);
Now... Another thing to consider is that realloc can fail. A common pattern for realloc that accounts for this is:
Point *reallocFunction(Point * r){
void *new_buffer = realloc(r, r[0].x*2*sizeof(Point));
if (!new_buffer)
{
// realloc failed, pass the error up to the caller..
return NULL;
}
r = new_buffer;
r[0].x*=2;
r[0].y++;
return r;
}
This ensures that you don't leak r when the memory allocation fails, and the caller then has to decide what happens when your function returns NULL...
But, some other things I'd point out about this code (I don't mean to sound like I'm nitpicking about things and trying to tear them apart; this is meant as constructive design feedback):
The names of variables and members don't make it very clear what you're doing.
You've got a lot of magic constants. There's no explanation for what they mean or why they exist.
reallocFunction doesn't seem to really make sense. Perhaps the name and interface can be clearer. When do you need to realloc? Why do you double the X member? Why do you increment Y? Can the caller make these decisions instead? I would make that clearer.
Similarly it's not clear what enter() is supposed to be doing. Maybe the names could be clearer.
It's a good thing to do your allocations and manipulation of member variables in a consistent place, so it's easy to spot (and later, potentially change) how you're supposed to create, destroy and manipulate one of these objects. Here it seems in particular like main() has a lot of knowledge of your structure's internals. That seems bad.
Use of the multiplication operator in parameters to realloc in the way that you do is sometimes a red flag... It's a corner case, but the multiplication can overflow and you can end up shrinking the buffer instead of growing it. This would make you crash and in writing production code it would be important to avoid this for security reasons.
You also do not seem to initialize r[0].y. As far as I understood, you should have a r[0].y=0 somewhere.
Anyway, you using the first element of the array to do something different is definitely a bad idea. It makes your code horribly complex to understand. Just create a new structure, holding the array size, the capacity, and the pointer.

Resources