xmlReaderForMemory crashes on 2nd time call [closed] - c

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
after making google for long time also, i am unable to find reason/solution for crashing of xmlReaderForMemory,still with valid parameters.
i have created two parser function using libxml,when i call individually they are working fine.But when i call one after another it is getting crashed on xmlReaderForMemory by giving error s follows:
First-chance exception at 0x7c918fea in nayak.exe: 0xC0000005: Access violation writing location 0x00000010.
Unhandled exception at 0x7c918fea in nayak.exe: 0xC0000005: Access violation writing location 0x00000010.
now i am giving the code of the two functions:
FIRST FUNCTION:
char* CB_omniParser(char *omnistring){
char *parseResult,;
const char *fileName = omnistring;
char *temp,*texttemp,*result=0;
int i,len=0,error;
xmlTextReaderPtr reader;
len= strlen(omnistring);
if(len==0)
return 0;
reader = xmlReaderForMemory(fileName,len,"",NULL,0);
if(reader){
temp = (char *) GlobalAlloc(GPTR, sizeof(char)*len);
parseResult = (char *) GlobalAlloc(GPTR,sizeof(char)*len+1);
while(error=xmlTextReaderRead(reader)) {
if(error==-1){
return 0; // on failure
}
switch(xmlTextReaderNodeType(reader)) {
case XML_READER_TYPE_ELEMENT:
temp = (char *)xmlTextReaderConstName(reader);
strcat(parseResult,temp);
strcat(parseResult,"#");
xmlTextReaderMoveToElement(reader);
continue;
case XML_READER_TYPE_TEXT:
temp = (char *)xmlTextReaderConstValue(reader);
strcat(parseResult,temp);
strcat(parseResult,"|");
continue;
}
}
xmlFreeTextReader(reader);
xmlCleanupParser();
return parseResult;//on success returns the parsed omni string
}
else
return 0; // on failure
}
Second Function:
char* CB_xmlParserFromMemory(char *xmlstring){
char *xmlParseresult;
char *temp;
int i,len,,error;;
xmlTextReaderPtr reader1;
len= strlen(xmlstring);
if(len==0)
return 0;
reader1 = xmlReaderForMemory(xmlstring,len,NULL,NULL,0);
if(reader1){
temp = (char *) GlobalAlloc(GPTR, sizeof(char)*len);
while(error=xmlTextReaderRead(reader1)) {
if(error==-1){
return 0; // on failure
}
switch(xmlTextReaderNodeType(reader1)) {
case XML_READER_TYPE_ELEMENT:
temp = (char *)xmlTextReaderConstName(reader1);
strcat(xmlParseresult,"\"");
strcat(xmlParseresult,temp);
strcat(xmlParseresult,"\"");
strcat(xmlParseresult,":");
xmlTextReaderMoveToElement(reader1);
continue;
case XML_READER_TYPE_TEXT:
temp = (char *)xmlTextReaderConstValue(reader1);
strcat(xmlParseresult,"\"");
strcat(xmlParseresult,temp);
strcat(xmlParseresult,"\"");
strcat(xmlParseresult,",");
continue;
}
}
xmlCleanupParser();
xmlFreeTextReader(reader1);
GlobalFree(temp);
return xmlParseresult;//on success returns the parsed omni string
}
else
return 0; // on failure
}
both the functions are working individually fine.but if i call one function after another then both crashes at above given place...ith same error..plz help me.....

I think it's a lucky day for me as i am having the opportunity to answer my own question...
Now i am happy as it is working perfectly fine at my end with out any issue, the issue was of memory(it's not that, what you are thinking after listening the word issue of memory).
The issue was being raised because of the statement:
xmlCleanupParser();
as i have used instead of
xmlInitParser ();
but now i will not give the reason,because you guys should also do some work...
I will give you the the URL which helped me to get out of this....

Related

Issues using realloc (old size)

I'm trying to use realloc function in C, to dynamically operate on a char array of strings (char**).
I usually get a realloc():invalid old size error after 41st cicle of the for loop and I really can't understand why.
So, thanks to everyone who will help me ^-^
[EDIT] I'm trying to make the post more clear and following your advices, as a "new active member" of this community, so thank you all!
typedef struct _WordsOfInterest { // this is in an header file containing just
char **saved; // the struct and libraries
int index;
} wordsOfInterest;
int main() {
char *token1, *token2, *save1 = NULL, file[LEN], *temp, *word, **tokenArr;
int n=0, ch,ch2, flag=0, size, init=0,position,currEdit,init2=0,tempEdit,size_arr=LEN,
oldIndex=0,totalIndex=0,*editArr,counterTok=0;
wordsOfInterest toPrint;
char **final;
toPrint.index = 0;
toPrint.saved = malloc(sizeof(char*)*LEN);
editArr = malloc(sizeof(int)*LEN);
tokenArr = malloc(sizeof(char*)*LEN);
final = malloc(sizeof(char*)*1);
// external for loop
for(...) {
tokenArr[counterTok] = token1;
// internal while loop
while(...) {
// some code here surely not involved in the issue
} else {
if(init2 == 0) {
currEdit = config(token1,token2);
toPrint.saved[toPrint.index] = token2;
toPrint.index++;
init2 = 1;
} else {
if((abs((int)strlen(token1)-(int)strlen(token2)))<=currEdit) {
if((tempEdit = config(token1,token2)) == currEdit) {
toPrint.saved[toPrint.index] = token2;
toPrint.index++;
if(toPrint.index == size_arr-1) {
size_arr = size_arr*2;
toPrint.saved = realloc(toPrint.saved, size_arr);
}
} else if((tempEdit = config(token1,token2))<currEdit) {
freeArr(toPrint, size_arr);
toPrint.saved[toPrint.index] = token2;
toPrint.index++;
currEdit = tempEdit;
}
}
}
flag = 0;
word = NULL;
temp = NULL;
freeArr(toPrint, size_arr);
}
}
editArr[counterTok] = currEdit;
init2 = 0;
totalIndex = totalIndex + toPrint.index + 1;
final = realloc(final, (sizeof(char*)*totalIndex));
uniteArr(toPrint, final, oldIndex);
oldIndex = toPrint.index;
freeArr(toPrint,size_arr);
fseek(fp2,0,SEEK_SET);
counterTok++;
}
You start with final uninitialized.
char **final;
change it to:
char **final = NULL;
Even if you are starting with no allocation, it needs a valid value (e.g. NULL) because if you don't initialize a local variable to NULL, it gets garbage, and realloc() will think it is reallocating a valid chunk of memory and will fail into Undefined Behaviour. This is probably your problem, but as you have eliminated a lot of code in between the declaration and the first usage of realloc, whe cannot guess what is happening here.
Anyway, if you have indeed initialized it, I cannot say, as you have hidden part of the code, unlistening the recommendation of How to create a Minimal, Reproducible Example
.
There are several reasons (mostly explained there) to provide a full but m inimal, out of the box, failing code. This allows us to test that code without having to provide (and probably solving, all or part) the neccesary code to make it run. If you only post a concept, you cannot expect from us complete, full running, and tested code, degrading strongly the quality of SO answers.
This means you have work to do before posting, not just eliminating what you think is not worth mentioning.
You need to build a sample that, with minimum code, shows the actual behaviour you see (a nonworking complete program) This means eliminating everything that is not related to the problem.
You need (and this is by far more important) to, before sending the code, to test it at your site, and see that it behaves as you see at home. There are many examples that, when eliminated the unrelated code, don't show the commented behaviour.
...and then, without touching anymore the code, send it as is. Many times we see code that has been touched before sending, and the problem dissapeared.
If we need to build a program, we will probably do it with many other mistakes, but not yours, and this desvirtuates the purpose of this forum.
Finally, sorry for the flame.... but it is necessary to make people read the rules.

Sending char* to char *[] [closed]

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 2 years ago.
Improve this question
Sorry for the long codes. I'm developing a command program that tokenizing the user commands. If I enter "Hello world "hi guys" ",
temp[0] = "Hello"
temp[1] = "world"
temp[2] = "hi guys"
Now I'm struggling with the store_token function. I have to print tokens like this.
tokens[0] = "Hello"
tokens[1] = "world"
tokens[2] = "hi guys"
temp is a temporary bridge that stores cut tokens. So I write like this
(*tokens)[i] = (*temp)[i]
because 'tokens' is char *[], and I want to access the element of 'tokens'
to store the char * of the temp.
Here is some problem. I can't figure out the (*tokens)[i] and I don't know
what it directs.
This is a problem in code readability. You have some code that almost works; but, because you have not invested in readaility, you can't find your error.
I would start by clarifying the "reset / complete the token operation" and "add to token" operations. If any code flow doesn't do one or the other, there's a bug.
for (int i = 0; i < clen; i++) {
if (*command == *"\"" ) {
isnested = !isnested;
continue;
} else if (*command == *"\n") {
toklen = 0;
ntoken++;
} else if (isspace(*command) && !(isnested)) {
if (doublespace) {
*command++;
continue;
} else {
doublespace = true;
ntoken++;
toklen = 0;
}
} else {
doublespace = false;
temp[ntoken][toklen] = *command;
toklen++;
}
*command++;
}
*nr_tokens = ntoken;
Assuming that adding to toklen indicates "add to the token" and toklen = 0 signals a "complete the token" I would rewrite the code
for (int i = 0; i < clen; i++) {
if (*command == *"\"" ) {
isnested = !isnested;
continue;
} else if (*command == *"\n") {
completeToken();
} else if (isspace(*command) && !(isnested)) {
if (doublespace) {
*command++;
continue;
} else {
doublespace = true;
completeToken();
}
} else {
doublespace = false;
addToken(*command);
}
*command++;
}
*nr_tokens = ntoken;
And now a few things are clear.
There are code flows through your algorithm that don't add to the token and don't complete the token. These code flows need simplified and put up front (so everyone can see what isn't important).
You don't add the quotes to a isnested token. Maybe your lexer strips the quotes; but, if it does, there's no token completion when we are exit the quotes.
Your lexer handles new lines without regard to the isnested variable. Odds are it should be adding the newline to the string if inside a set of quotes.
Your lexer is very concerned with double spaces. Normally, if spaces are being stripped, they are stripped without regard to how many exist.
Even in small blocks of code, readability matters. C's history ignores modern readability rules, as the rules came out after the language; but, you would do well to apply them anyway, so you can get the modern readability benefits within the C operating enviornment.

linux kernel + conditional statements

I basically am running into a very odd situation in a system call that I am writing. I want to check some values if they are the same return -2 which indicates a certain type of error has occurred. I am using printk() to print the values of the variables right before my "else if" and it says that they are equal to one another but yet the conditional is not being executed (i.e. we don't enter the else if) I am fairly new to working in the kernel but this seems very off to me and am wondering if there is some nuance of working in the kernel I am not aware of so if anyone could venture a guess as to why if I know the values of my variables the conditional would not execute I would really appreciate your help
//---------------------------------------//
/* sys_receiveMsg421()
Description:
- Copies the first message in the mailbox into <msg>
*/
asmlinkage long sys_receiveMsg421(unsigned long mbxID, char *msg, unsigned long N)
{
int result = 0;
int mboxIndex = checkBoxId(mbxID);
int msgIndex = 0;
//acquire the lock
down_interruptible(&sem);
//check to make sure the mailbox with <mbxID> exists
if(!mboxIndex)
{
//free our lock
up(&sem);
return -1;
}
else
mboxIndex--;
printk("<1>mboxIndex = %d\nNumber of messages = %dCurrent Msg = %d\n",mboxIndex, groupBox.boxes[mboxIndex].numMessages, groupBox.boxes[mboxIndex].currentMsg );
//check to make sure we have a message to recieve
-----------CODE NOT EXECUTING HERE------------------------------------------------
if(groupBox.boxes[mboxIndex].numMessages == groupBox.boxes[mboxIndex].currentMsg)
{
//free our lock
up(&sem);
return -2;
}
//retrieve the message
else
{
//check to make sure the msg is a valid pointer before continuing
if(!access_ok(VERIFY_READ, msg, N * sizeof(char)))
{
printk("<1>Access has been denied for %lu\n", mbxID);
//free our lock
up(&sem);
return -1;
}
else
{
//calculate the index of the message to be retrieved
msgIndex = groupBox.boxes[mboxIndex].currentMsg;
//copy from kernel to user variable
result = copy_to_user(msg, groupBox.boxes[mboxIndex].messages[msgIndex], N);
//increment message position
groupBox.boxes[mboxIndex].currentMsg++;
//free our lock
up(&sem);
//return number of bytes copied
return (N - result);
}
}
}
UPDATE: Solved my problem by just changing the return value to something else and it works fine very weird though
Please remember to use punctuation; I don't like running out of breath while reading questions.
Are you sure the if block isn't being entered? A printk there (and another in the corresponding else block) would take you one step further, no?
As for the question: No, there isn't anything specific to kernel code that would make this not work.
And you seem to have synchronization covered, too. Though: I see that you're acquiring mboxIndex outside the critical section. Could that cause a problem? It's hard to tell from this snippet, which doesn't even have groupBox declared.
Perhaps numMessages and/or currentMsg are defined as long?
If so, your printk, which uses %d, would print just some of the bits, so you may think they're equal while they are not.

Why am I getting core dumped? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Please help me. I can't figure out why I get a core dumped when I run this program. Before returning anything I can print all_albums_p just fine. Why am I getting core dumped?
#include "music_server.h"
struct album_ {
int num_tracks;
char **tracks;
int **playlist_hits;
};
typedef struct album_ album;
album *parse_album(FILE *album_file,int *number_of_albums){
int number_of_album,number_of_tracks,number_of_charaters;
int i,j;
char dummy_space;
int *p;
fscanf(album_file,"%d", &number_of_album);
*number_of_albums = number_of_album;
album *all_albums_p = (album *)malloc(sizeof(album)*number_of_album);
for(j=0;j<number_of_album;j++){
fscanf(album_file,"%d", &all_albums_p[j].num_tracks);
all_albums_p[j].tracks = calloc(all_albums_p[j].num_tracks,sizeof(char));
all_albums_p[j].playlist_hits = calloc(all_albums_p[j].num_tracks,sizeof(int));
/*Line 27*/ for(i=0;i<all_albums_p[j].num_tracks;i++){
fscanf(album_file,"%d", &number_of_charaters);
all_albums_p[j].tracks[i] = (char *)calloc(number_of_charaters+1,sizeof(char));
all_albums_p[j].playlist_hits[i] = (int *)malloc(sizeof(int));
all_albums_p[j].playlist_hits[i] = 0;
fscanf(album_file," ",dummy_space);
fscanf(album_file, "%[^\n]s", all_albums_p[j].tracks[i]);
}
}
return all_albums_p;
}
main(int argc, char *argv[]){
int i,j;
int *number_of_albums,*number_of_tracks,a;
a=0;
number_of_albums = &a;
album *all_tracks_ptr;
album_file = fopen(argv[1],"r");
transaction_file = fopen(argv[2],"r");
if((album_file == NULL) || (transaction_file == NULL)){
printf("Either %s or %s could not be open");
}else{
all_tracks_ptr = parse_album(album_file,number_of_albums);
int number_of_tracks[*number_of_albums];
}
}
errors:
Bus Error (core dumped)
(gdb) bt
#0 0xff277c9c in _smalloc () from /lib/libc.so.1
#1 0xff277d10 in malloc () from /lib/libc.so.1
#2 0xff263830 in calloc () from /lib/libc.so.1
#3 0x00010dd8 in parse_album (album_file=0xff3675bc,
number_of_albums=0xffbff894) at functions.c:27
#4 0x00010b80 in main (argc=3, argv=0xffbff90c) at project3.c:19
You should allocate sizeof(char*) below instead of sizeof(char)
all_albums_p[j].tracks = alloc(all_albums_p[j].num_tracks,sizeof(char*));
Since that looks like a Unix message ("Bus Error (core dumped)) I will assume you are using some flavor of Unix.
So, compile your program with debugging info output turned on and with optimization turned off. If you're using gcc or something gcc-compatible, that would be the -g -O0 command line options.
Then run your program and have it crash. Locate the core dump (I'll call it corefile in this example) and then type:
gdb programname corefile
Then when you get the gdb prompt, type bt (for backtrace) to see the program's stackframe. That will tell you where the program crashed and you can examine that part of your program more closely.
Update:
I think your problem is here:
all_albums_p[j].tracks = calloc(all_albums_p[j].num_tracks,sizeof(char));
album.tracks is defined as char**. However, what you're assigning to all_albums_p[j].tracks is a block of memory the size of num_tracks char. You need to assign to it a block of memory big enough to hold num_tracks char *. So you probably need to change the line to:
all_albums_p[j].tracks = (char **) calloc(all_albums_p[j].num_tracks,sizeof(char *));
Use a debugger or valgrind and figure out what line the problem is occurring on. Then you will know what part of your code is bad.

Running out of memory.. How?

I'm attempting to write a solver for a particular puzzle. It tries to find a solution by trying every possible move one at a time until it finds a solution. The first version tried to solve it depth-first by continually trying moves until it failed, then backtracking, but this turned out to be too slow. I have rewritten it to be breadth-first using a queue structure, but I'm having problems with memory management.
Here are the relevant parts:
int main(int argc, char *argv[])
{
...
int solved = 0;
do {
solved = solver(queue);
} while (!solved && !pblListIsEmpty(queue));
...
}
int solver(PblList *queue) {
state_t *state = (state_t *) pblListPoll(queue);
if (is_solution(state->pucks)) {
print_solution(state);
return 1;
}
state_t *state_cp;
puck new_location;
for (int p = 0; p < puck_count; p++) {
for (dir i = NORTH; i <= WEST; i++) {
if (!rules(state->pucks, p, i)) continue;
new_location = in_dir(state->pucks, p, i);
if (new_location.x != -1) {
state_cp = (state_t *) malloc(sizeof(state_t));
state_cp->move.from = state->pucks[p];
state_cp->move.direction = i;
state_cp->prev = state;
state_cp->pucks = (puck *) malloc (puck_count * sizeof(puck));
memcpy(state_cp->pucks, state->pucks, puck_count * sizeof(puck)); /*CRASH*/
state_cp->pucks[p] = new_location;
pblListPush(queue, state_cp);
}
}
}
free(state->pucks);
return 0;
}
When I run it I get the error:
ice(90175) malloc: *** mmap(size=2097152) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Bus error
The error happens around iteration 93,000.
From what I can tell, the error message is from malloc failing, and the bus error is from the memcpy after it.
I have a hard time believing that I'm running out of memory, since each game state is only ~400 bytes. Yet that does seem to be what's happening, seeing as the activity monitor reports that it is using 3.99GB before it crashes. I'm using http://www.mission-base.com/peter/source/ for the queue structure (it's a linked list).
Clearly I'm doing something dumb. Any suggestions?
Check the result of malloc. If it's NULL, you might want to print out the length of that queue.
Also, the code snippet you posted didn't include any frees...
You need to free() the memory you've allocated manually after you're done with it; dynamic memory doesn't just "free itself"

Resources