Malloc call crashing, but works elsewhere - c

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.

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!

Segmentation Fault in Initializing a structure

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.

SIGTRAP when calling the free() function

I'm getting a SIGTRAP signal when trying to free an dynamically created array, and have no idea on why.
I'm allocating the array like this:
int* visited = (int*) malloc( l.nodeCount * sizeof(int));
(l.nodeCount is an integer. In the instance of the program I get this error, it is set to 12.)
And when I try to free(visited), I get the SIGTRAP signal in the debugger.
The whole function is this one:
int Graph_GetSmallestPathCount(AdjacencyList l, int destination){
//One path if destination is root
if(destination == 0) return 1;
if(l.nodeCount == 0)
return 0;
Queue reading = Queue_NewQueue();
Queue storing = Queue_NewQueue();
/*Allocates visited array*/
int* visited = (int*) calloc( l.nodeCount, sizeof(int));
/*Visited array initialization*/
int i;
for(i = 0; i < l.nodeCount; i++)
visited[i] = 0;
/*Marks root node and enqueues it*/
visited[0] = 1;
Queue_Enqueue(&reading, 0);
//While there are nodes to read
while(!Queue_IsEmpty(reading))
{
//Dequeues a node
int v = Queue_Dequeue(&reading);
//Gets it's adjacency list
List* currentList = AdjacencyList_GetAdjacentNodes(l, v);
listCell* auxCell = currentList->head->next;
//While there are nodes in it's adjacency list
while(auxCell != NULL){
//Enqueues it if it has not been visited
if(visited[auxCell->data] == 0){
Queue_Enqueue(&storing, auxCell->data);
}
//Adds to the paths to that node
visited[auxCell->data] += visited[v];
auxCell = auxCell->next;
}
//When the queue ends
if(Queue_IsEmpty(reading)){
//If the destination has been reached, return
if(visited[destination] > 0){
Queue_Destroy(&reading);
Queue_Destroy(&storing);
return visited[destination];
}
else{
//Switch queues
Queue_Destroy(&reading);
reading = storing;
storing = Queue_NewQueue();
}
}
}
//Destination has not been reached before end of algorithms. Deallocate everything and return 0
free(visited);
Queue_Destroy(&reading);
Queue_Destroy(&storing);
return 0;
}
Sorry for the lack of comments, I did this on a run and didn't put any in. Also sorry for the printf overload, I put them there while trying to pinpoint the problem.
EDIT: I cleaned it up a little.
The weird thing is that the program works for certain inputs and doesn't for others.
Hope someone can help me out =D
I can't tell you why you get a SIGTRAP as you haven't published a minimal example.
However, I can tell you how to find out out yourself:
Make your program readable. Use one instruction per line. The indent tool is your friend. Sure, that won't fix the bug, but it will make it easier for you to find it.
Don't malloc like that. There is no need to cast the return value of malloc, and using calloc(l.nodeCount, sizeof (int)); or similar is more readable anyway.
What SIGTRAP actually means is you've hit a breakpoint instruction. No doubt what's actually happening is that you've jumped to something which is not your code, and might not be code at all, but contains the binary code for a breakpoint. Why did that happen? The normal cause would be memory corruption, particularly stack corruption. I'm guessing free() is corrupting its own stack. And I'd guess the reason for that is because you are (somewhere) writing to memory outside the memory you've allocated. To test this, run your program with the malloc()/calloc() immediately followed by the free() and an exit(0). If that works, you know the issue is something you are doing between.
We can't tell what you are doing between because you haven't (thankfully) posted the full program, but try running it under valgrind. When you get an out-of-range write, valgrind will normally pick it up. Fix every valgrind warning. That doesn't guarantee a solution, but will find one 95% of the time in my experience.
Also note that return visited[destination]; appears to exit the function without free()-ing visited, which is thus a memory leak.
First, don't call malloc() like that. l.nodeCount * sizeof(int) could potentially exceed INT_MAX, and you'll either have a security hole or if you're lucky, a crash.
Instead, use calloc(l.nodeCount, sizeof(int)).
You should also check the return value of malloc or calloc for NULL in the event your program runs out of memory to allocate.
Found the answer. There was indeed a chance that on specific cases the array would be created with one element less than it should. My bad.
Thanks to all who helped =D

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;

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