corruption of the heap, error in C [closed] - c

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 5 years ago.
Improve this question
well I dont need to explain too much, this function get this error at the line I marked all the time, only in this function there are allocations of memoery, please help me find out where is the issue...(read some other topics with that here, but nothing helped me solve it)
ERROR:"Windows has triggered a breakpoint in sapProject.exe.
This may be due to a corruption of the heap, which indicates a bug in sapProject.exe or any of the DLLs it has loaded.
"
void storeTok(char * lexem,int line,enum keywords typeof)
{
int ind;
if(tokens.size%100==0)
{
if(tokens.size==0)
{
tokens.ptrInd=-1;
tokens.first=(node*)malloc(sizeof(node));
tokens.first->back = NULL;
tokens.first->next = NULL;
tokens.last=tokens.first;
}
else
{
node * nodenz=(node*)malloc(sizeof(node)); /error is here
nodenz->back = tokens.last;
nodenz->next = NULL;
tokens.last->next=nodenz;
tokens.last=tokens.last->next;
tokens.last=nodenz;
}
}
// general
ind=tokens.size-(tokens.size/100)*100;
tokens.last->tokens[ind].type=typeof;
tokens.last->tokens[ind].linen=line;
tokens.last->tokens[ind].lexema=lexem;
tokens.size++;
}
Thanks!
edit(except this, there is also a header(and thats it..):
typedef struct token
{
char * lexema ;
int linen;
enum keywords type;
}token;
typedef struct node
{
struct node * next,*back;
token tokens [50];
}node;
typedef struct LL
{
struct node * last, *first, * ptr;
int size,ptrInd;
}LL;
LL tokens;
void storeTok(char * lexem,int line,enum keywords typeof);
main func:
void main()
{
int i;
for(i=0;i<26;++i)
{
storeTok("blabla",1,END);
storeTok("sdfasd",1,START);
storeTok("sfadds",1,IF);
storeTok("gvdfd",1,THEN);
storeTok("dfsfd",1,ELSE);
}
storeTok("dfsfd",1,EOF_);
}

That line is probably the victim. The code that corrupted the heap is elsewhere. You can use a tool like valgrind or a similar tool to find it. (Or give us enough code to replicate the error and we can track it down for you.)

Related

Invalid use of incomplete type error in c

I know that this question already got answered a lot but I've read a lot of threads and I couldn't find a answer for me.
I get the error
invalid use of incomplete type ‘struct PackAnimalImplementation’
if(animal->type != 0 && current == caravan)
for the following code:
#include <stdlib.h>
#include "caravan.h"
#include "general.h"
#define COUNT_CARAVANS 5
/*
Basically our Node
*/
struct CaravanImplementation{
int length;
PackAnimal animal;
struct CaravanImplementation* next;
};
Caravan head = (Caravan)malloc(sizeof(struct CaravanImplementation));
void add_pack_animal(Caravan caravan, PackAnimal animal)
{
Caravan current = head;
while(current != 0){
if(animal->type != 0 && current == caravan)
{
current->animal = animal;
return;
}
}
}
Here is the struct I want to use, it's in the file pack_animal.cpp and got forward declared in the pack_animal.h file:
Forward Declaration:
typedef struct PackAnimalImplementation* PackAnimal;
Definition in cpp file:
struct PackAnimalImplementation {
AnimalType type; //The AnimalType is an enum with 2 values: Horse and Camel
const char *name;
int max_speed;
int load;
Caravan caravan;
};
The caravan.h, pack_animal.h and pack_animal.cpp files don't have any issues. This is a school exercise and my teacher made them and told me they actually work. Would be glad if someone could help me.
You can't hide the definition of PackAnimalImplementation away in a .cpp file. Anything that wants to "do things" with objects of that type need to know what it looks like.
Move it to the header file, or engage in some PIMPL antics if you want to hide it all away (but then you're going to need to provide some accessor functions, and free ones at that if you're targeting C compatibility).
Further reading:
When can I use a forward declaration?

How to analyze this FIFO program? [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 5 years ago.
Improve this question
Here are some pieces of the program that completes FIFO buffer pool. I don't know how does it complete. Does anyone help me to analyze it?
This is a struct of FlameHandle, this struct stores total flames, the first frame, and the last frame.
typedef struct FlameHandle{
PageFlame *first;
PageFlame *last;
PageFlame *totalFlames;
int numWriteIO;
int numReadIO;
} FlameHandle;
This is a struct of PageFlame, this struct stores info of each flame.
typedef struct PageFlame{
char *data;
PageNumber pageNum;
bool isDirty;
int fixCount;
struct PageFlame *next;
struct PageFlame *prev;
} PageFlame;
This is a struct of BM_BufferPool
typedef struct BM_BufferPool {
char *pageFile;
int numPages;
ReplacementStrategy strategy;
void *mgmtData; // use this one to store the bookkeeping info your buffer
// manager needs for a buffer pool
} BM_BufferPool;
This is a struct of BM_PageHandle
typedef struct BM_PageHandle {
PageNumber pageNum;
char *data;
} BM_PageHandle;
This is a function pinPage.
RC pinPage(BM_BufferPool *const bm, BM_PageHandle *const page, const PageNumber pageNum)
{
FlameHandle *FH;
FH = bm->mgmtData;
page->data = (char*)malloc(sizeof(char)*PAGE_SIZE);
SM_FileHandle fh;
PageFlame *pf;
openPageFile(bm->pageFile,&fh);
page->pageNum = pageNum;
for(int i=0; i<bm->numPages;i++)
{
pf = &(FH->totalFlames)[i];
if((FH->totalFlames[i]).pageNum == NO_PAGE)
{
FH->totalFlames[i].pageNum = pageNum;
pf->fixCount++;
ensureCapacity(pageNum+1,&fh);
//Reads new flame from fh and stores it to (FH->first)->data).
readBlock(pageNum,&fh,(FH->first)->data);
FH->numReadIO++;
strcpy(page->data,(FH->first)->data);
FH->last = FH->first;
if(FH->last->next == NULL)
{
FH->first = FH->totalFlames;
}
else
{
(FH->first) = (FH->last)->next;
}
return RC_OK;
}
}
}
In this function, It needs to store a new flame in an empty flame (pageNum == NO_PAGE), and at the same time, it needs to keep the FIFO sequence. I really cannot understand the semantics of following code:
if(FH->last->next == NULL){
FH->first = FH->totalFlames;
}else
{
(FH->first) = (FH->last)->next;
}
Does anyone can help me?
Here is the link of the whole project on GitHub:
https://github.com/randywhisper/assign_cs525/blob/master/assign2/buffer_mgr.c
Remember that the code you pasted there is RS_FIFO.
You can run the code using your pen.
In initBufferPool function, you create a Doubly linked list named PageFlame.
PageFlame have N totalPageFlames.
PageFlame's fist points to totalPageFlames[0], last points to end.
FIFO is first in first out.
Suppose you have a PageFlame(length 4) like a,b,c,d.
Here comes your snippet code.
FH->last = FH->first, last->next is b, not NULL, so goes to (FH->first) = (FH->last)->next;.
That means , last points to a while first points to b.
Next run, last points to b while first points to c.
a is read first and then first moves to next one b.
I think this is clear.
When there is only one element d and d->next is NULL.
So first will move from last out element c to d. When next element e comes in the queue, first will move to the e and last stay in d.
RS_FIFO, first in first out. That is it.

adding of alternative node which contain interger value in give linked list? [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 8 years ago.
Improve this question
Hi i wrote a code to add alternative node which contain integer value in single linked list.My code get crash please help me to fix it.
example lets take there are 6 node in singly linked list 3 5 8 6 4 9
then o/p should be 3+8+4 and 5+6+9 and my approach is wrong i guess please help me to fix it .In below code i am returning only one alternative value i.e 3+8+4 ?
void add(struct st **ptr)
{
struct st *curr,*prev;
curr=*ptr;
while(curr->next!=NULL)
{
if(curr->next->next->data!=NULL) //checking alternative node is present or
//or not and to avoid crash
{
sum= curr->data + curr->next->next->data;
}
else
{
sum= curr->data;
}
curr= curr->next;
}
prev=*ptr;
while(prev->next !=null)
{
prev=prev->next;
if(prev->next->next->data!=NULL)
{
sum=prev->data+prev->next->next->data;
}
else
{
sum=prev->data;
}
}
return sum;
}
First of all, It is not possible to return twice from a function. You can use call by reference as an alternative to it. Before the function call you can create two variables for two sums, initialize them to zero and send them as reference.
int sum_even = 0; //sum of elements at even position
int sum_odd = 0; //sum of elements at odd position
add(&start, &sum_even, &sum_odd); // call by reference
//sum_even and sum_odd will have the respective sums
Now for problem on linked lists it is advisable that you sit with pen and paper and try to trace each line of code you write. Testing boundary conditions is essential.
I have written a possible solution for your problem.
void add(struct st **ptr, int *sum_even, int *sum_odd)
{
struct st *even, *odd;
even = *ptr;
if(even->next) odd = even->next;
else odd = NULL;
while(even != NULL)
{
*sum_even += even->data;
if(even->next == NULL) break;
even = even->next->next;
}
while(odd != NULL)
{
*sum_odd += odd->data;
if(odd->next == NULL) break;
odd = odd->next->next;
}
}
if(curr->next->next->data!=NULL)
Here you should also check curr->next->next is not NULL.
Also, your if condition is also not correct. You should check for next!=NULL than data.
So update your ifs to
if(curr->next->!=NULL && curr->next->next->data!=NULL)
Also, try to use gdb or some other debugger to debug and see why your program is crashing and what are the problems.

Bad memory access while calling function

Actually i developing using unit test.
But i break down my code in other form to ask for the error that i faced.
I have these declaration in my header file
typedef struct
{
void *topOfStack;
}Stack;
typedef enum {NUMBER,OPERATOR,IDENTIFIER}Token;
int operatorEvaluate(Stack *numberStack , Stack *operatorStack);
void * pop(Stack *stack);
The following is the respective source file
#include "try.h"
void *pop(Stack *numberStack)
{
Token *newToken = NUMBER;
return newToken;
}
int operatorEvaluate(Stack *numberStack , Stack *operatorStack)
{
Token *first = (Token*)pop (numberStack);
if(numberStack != operatorStack)
{
if(*first == NUMBER)
return 1;
}
return 0;
}
This is the source file that i call the functions which is main
#include "try.h"
#include <stdio.h>
int main ()
{
Stack numberStack;
Stack operatorStack;
int num;
num = operatorEvaluate(&numberStack , &operatorStack);
printf("This is the returned value: %d",num);
return 0;
}
When i tried to compile, the unit test tell me that bad memory access.
So i try to use eclipse to compile these, and windows tells that the .exe had stop working.
Hope someone can help me, i stuck for a long time...
Enable compiler warnings.
In particular, this makes zero sense:
Token *newToken = NUMBER;
That's a pointer, and you're assigning a value.
I cannot propose a fix, as I have no idea what you're doing.
That pop() function isn't touching the stack, and is returning an enum converted to a pointer. If you try to access anything through that pointer, it's going to provoke undefined behavior.
Your pop function is wrong in a few ways. You probably want it to actually pop your stack, rather than return a constant (which it isn't doing either, by the way!)...something like this:
void *pop(Stack *numberStack)
{
return numberStack->topOfStack;
}
but if you do that it'll still crash, because you never initialize your stack OR fill the topOfStack pointer.

Using a function pointer [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have a function in C that is crashing my code and I'm having a hard time figuring out what is going on. I have a function that looks like this:
#define cond int
void Enqueue(cond (*cond_func)());
cond read() {
return IsEmpty(some_global); // Returns a 1 or a 0 as an int
}
Enqueue(&read);
However, when running the above, it segfaults as soon as Enqueue is called. It doesn't even execute anything inside the function. I ran gdb and it just shows it dying as soon as Enqueue is called- no statements are processed within it. Any idea what is going on? Any help would be appreciated.
Can you give more information about the code because according to my interpretation the code is working fine.I have tried this-
#define cond int
void Enqueue(cond (*cond_func)());
cond read()
{
int some_global=1;
return IsEmpty(some_global); // Returns a 1 or a 0 as an int
}
int IsEmpty()
{
return 1;
}
void Enqueue(cond (*cond_func)())
{
printf("Perfect");
return 0;
}
int main()
{
Enqueue(&read);
return 0;
}
And it is working fine.
#define cond int
was meant to be:
typedef int cond;
Although defining an alias for your function pointer might be much more reasonable here, for example:
typedef int (*FncPtr)(void);
int read() {
printf("reading...");
}
void foo(FncPtr f) {
(*f)();
}
int main() {
foo(read);
return 0;
}
This works fine:
#include <stdio.h>
#include <stdbool.h>
typedef bool cond;
void Enqueue(cond (*cond_func)(void)) {
printf("In Enqueue()...\n");
cond status = cond_func();
printf("In Enqueue, 'status' is %s\n", status ? "true" : "false");
}
bool IsEmpty(const int n) {
return true;
}
cond my_cond_func(void) {
printf("In my_cond_func()...\n");
return IsEmpty(1);
}
int main(void) {
Enqueue(my_cond_func);
return 0;
}
Your problem is likely coming from somewhere else, such as your definition of Enqueue() which you don't provide, or the fact your function is called read() and is conflicting with the more common function of that name.

Resources