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.
Related
I'm working in C, Linux terminal. I need to find a pattern in a text and recolor it. GDB debugging can locate the function that is causing the problem via (gdb) backtrace, but it shows me a terrible message when I try to find the exact line:
Error
Program received signal SIGSEGV, Segmentation fault.
strstr_sse2_unaligned ()
at ../sysdeps/x86_64/multiarch/strstr-sse2-unaligned.S:40
40 ../sysdeps/x86_64/multiarch/strstr-sse2-unaligned.S: No such file or dir
ectory.
(gbd)
The broken function is find_and_recolor:
char* my_replace(char *text, char* replacement)
{
int lgreplacement = strlen(replacement);
int lgtext = strlen(text);
char *aux = (char*)malloc((lgreplacement + lgtext + 10) * sizeof(char));
strcpy(aux, replacement);
strcat(aux, text);
return(aux);
}
char* find_and_recolor(char* text, char* pattern)
{
int lgpattern = strlen(pattern);
int lgreplace = lgpattern + 10;//there are exactly 10 characters that must be inserted along the pattern word
int dif = 0;
char *p;
char *replacement = (char*)malloc(lgreplace * sizeof(char));
strcpy(replacement, "\e[0;31m");
strcat(replacement, pattern);
strcat(replacement, "\e[m");//to recolor a word in red, that word must be surrounded by those characters
while(p = strstr(text + dif, pattern))
{
p = my_replace(p, replacement);
p += lgreplace;
dif = p - text;
}
free(replacement);
return strdup(text);
}
it shows me a terrible message when I try to find the exact line:
There is nothing terrible, weird or unusual about this message, you just need to learn proper debugging technique.
What's happening is that the segmentation fault doesn't happen in your code, it happens inside GLIBC code (inside strstr), because you called strstr with bad arguments.
To find which call to strstr that was, use GDB up command to step out of GLIBC code, and into your code. Once you are inside find_and_recolor, you would be able to see the exact line, and print values of text, dif and pattern which caused your crash (assuming you compiled your code for debugging, i.e. with the -g flag).
Updating diff to p-text in while loop where both pointer points to different array doesn't make sense. It is undefined behavior.
Also code has other issues.
Uninitialized variable.
Less optimized as number of call can be reduced.
I got a struct Chat
struct Chat
{
int m_FD;
int m_BindPort;
char m_NameLength;
char* m_Name;
char m_PeerCount;
char** m_PeerList;
} typedef Chat_t;
i'm initializing it with this function:
int chat_init(Chat_t* this, unsigned int nameLen, char* name, unsigned short int bindPort, unsigned int peerCount, char** peerList)
{
this->m_NameLength = nameLen;
this->m_Name = malloc(sizeof(char) * (nameLen+1));
strcpy(this->m_Name, name);
this->m_BindPort = bindPort;
this->m_PeerCount = peerCount;
this->m_PeerList = malloc(sizeof(char*) * peerCount);
for(int i=0; i<peerCount; i++)
{
this->m_PeerList[i] = malloc(sizeof(char) * 16); // enough for xxx.xxx.xxx.xxx\0
strcpy(this->m_PeerList[i], peerList[i]);
}
//Socket initialization for TCP connection...
//Commenting this out doesn't change anything so i'm hiding it for simplification
return 0;
}
After that i'm calling a second function
int chat_communicate(Chat_t* this)
{
printf("2\n");
fflush(stdout);
//Some stuff that doesn't matter because it isn't even called
return retVar;
}
in main like this
void main(void)
{
char* peerList[1];
char username[USERNAME_MAX_LEN];
int initRet;
int loopRet;
Chat_t chat;
peerList[0] = "192.168.2.2";
memset(username, 0, USERNAME_MAX_LEN);
printf("Please enter your user name: ");
scanf("%s", username);
username[USERNAME_MAX_LEN-1] = 0;
initRet = chat_init(&chat, strlen(username), username, 1234, 1, peerList);
printf("File Descriptor: %d\n", chat.m_FD);
printf("Binding Port: %d\n", chat.m_BindPort);
printf("Name Length: %d\n", chat.m_NameLength);
printf("Name: %s\n", chat.m_Name);
printf("Peer Count: %d\n", chat.m_PeerCount);
for(int i=0; i< chat.m_PeerCount; i++)
{
printf("Peer[%d]: %s\n", i, chat.m_PeerList[i]);
}
printf("1");
ret = chat_communicate(&chat);
//Even more Stuff that isn't even called
}
My program outputs the following
File Descriptor: 3
Binding Port: 1234
Name Length: 4
Name: User
Peer Count: 1
Peer[0]: 192.168.2.2
1
Segmentation Fault
It compiles without errors or even warnings.
You can also assume that every string is null-Terminated The stuff i replaced with comments itn't that complicated but just too much to show.
Every value inside the struct is printed with printf right before but when passing this very struct per reference the application crashes.
What i want to know is why i'm getting this Segmentation Fault. Since it appeared while calling a function i thought it is some kind of layout problem but i havn't find anything like that.
Addition:
Because some people weren't able to believe me that the code i hid behind "some stuff" comments doesn't change anything i want to state this here once again. This code just contains a tcp socket communication and only performs read-operations. I also am able to reproduce the error mentioned above without this code so please don't get stuck with it. Parts does not influence the object under observation at all.
Among other potential problems,
this->m_PeerList = malloc(sizeof(char)*peerCount);
is clearly wrong.
m_PeerList is a char **, yet you're only allocating peerCount bytes, which only works if a char * pointer is one byte on your system - not likely.
Replace it with something like
this->m_PeerList = malloc(peerCount * sizeof( *( this->m_peerList ) ) );
Note that sizeof( char ) is always one - by definition.
You're not allocating enough memory for the this->m_Name. It should be on more than this if you want it to store the null-terminated string of the name.
That, or we need more information about the peerList.
Now that you have posted an almost complete code, I was able to spot two problems next to each other:
int chat_init(Chat_t* this, unsigned int nameLen, char* name, unsigned short int bindPort, unsigned int peerCount, char** peerList)
{
this->m_NameLength = nameLen;
this->m_Name = malloc(sizeof(char) * (nameLen + 1)); // correct
//< this->m_Name = malloc(sizeof(char) * nameLen); // wrong
strcpy(this->m_Name, name); // correct
//< memcpy(this->m_Name, name, nameLen); // wrong
...
The lines starting with //< is your original code:
Here you don't allocate enough space, you need to account for the NUL terminator:
this->m_Name = malloc(sizeof(char) * nameLen);
And here you don't copy the NUL terminator:
memcpy(this->m_Name, name, nameLen);
You really need to be aware how strings work in C.
Why don't you debug it yourself. If using GCC, compile your code with options -g -O0. Then run it with gdb:
gdb ./a.out
...
(gdb) r
If it crashes do:
(gdb) bt
This will give exactly where it crashes.
Update: There may be potential problems with your code as found by other users. However, memory allocation related issues will not crash your application just on calling function chat_communicate. There could be different reasons for this behaviour ranging from stack overflow to improper compilation. Without seeing the whole code it is very difficult to tell. Best advice is to consider review comments by other users and debug it yourself.
I asked a question earlier about this program and was able to resolve it--the good news is my program is working now! The bad news is that it only works when I run it through gdb. Whenever I normally compile the program it'll crash, but running it through gdb gives correct output and allows it to exit normally.
I read Dennis Yurichev's post on debugging this sort of problem with the stack or something in gdb, but I'm still pretty new to programming so I have no idea what I am doing.
Here is the output from attaching gdb to the process ID of the program and then dumping the stack:
Breakpoint 1, 0x74337480 in OutputDebugStringA () from C:\WINDOWS\SysWOW64\KernelBase.dll
(gdb) bt
#0 0x74337480 in OutputDebugStringA () from C:\WINDOWS\SysWOW64\KernelBase.dll
#1 0x77478a64 in msvcrt!_invalid_parameter () from C:\WINDOWS\SysWOW64\msvcrt.dll
#2 0x77425a20 in wctype () from C:\WINDOWS\SysWOW64\msvcrt.dll
#3 0x00010001 in ?? ()
#4 0x77493a09 in msvcrt!fscanf_s () from C:\WINDOWS\SysWOW64\msvcrt.dll
#5 0x7749399b in msvcrt!fscanf () from C:\WINDOWS\SysWOW64\msvcrt.dll
#6 0x00401d0d in main () at ZigSort.c:377
I think it's saying it's crashing due to invalid input or something from fscanf, but that doesn't make sense...
The line referenced (main() line 377) is the first fscanf in here:
int main(void)
{
//initializing file pointer
FILE * ifp;
ifp = fopen("zigzag.txt", "r");
int n;
//getting number of values
fscanf(ifp, "%d", &n); //**LINE 377 RIGHT HERE**
//reading values into a queue
queue_t * data = queue_create();
int ipt;
for(int i=0; i<n; i++)
{
fscanf(ifp, "%d", &ipt);
queue_enqueue(data, ipt);
}
//creating a stack of queues
run_stack_t * runstack = run_stack_create();
queue_t * run = queue_create();
//finding runs and pushing them onto the stack
int runs = 0;
int *runpoint = &runs;
while(queue_is_empty(data) != 1)
{
run = extract_next_run(data);
run_stack_push(runstack, run);
*runpoint += 1;
optimizestack(runstack, runpoint);
}
//merging queues together in sorted order
data = run_stack_pop(runstack);
queue_t * merger;
runs -= 1;
for(int i=0; i<runs; i++)
{
merger = run_stack_pop(runstack);
data = merge(merger, data);
}
queue_destroy(merger);
//output
printqueue(data);
//freeing memory
queue_destroy(data);
//run_stack_destroy(runstack, runpoint);
free(runstack);
free(runpoint);
fclose(ifp);
}
and the zigzag.txt file that is read in is here:
10
9 8 7 6 8 4 2 3 2 1
I'm happy to try anything or include any other information that may be necessary, I'm just not sure how to solve this problem.
Thanks in advance!
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 7 years ago.
Improve this question
I've encountered some strange behaviour in my program.
When I run my program 3-4 times and close it immediately, it's starting to give me segmentation faults before it even starts. When I haven't opened it for a while it opens the first 2-3 times without problem and then again seg faults.
I am open to suggestion on what can cause this kind of problem.
The project is quite big so I don't know where exactly to look so if someone wants to see the source code, here you go :
https://github.com/rokn/Helsys3
Let me break down a debugging session for you, but in future you better do that yourself.
If the problem can be easily reproduced, it is quite trivial to fix it:
gdb ./GAME
(gdb) r
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b2d10c in ?? () from /usr/lib/x86_64-linux-gnu/libSDL2-2.0.so.0
(gdb) bt
#0 0x00007ffff7b2d10c in ?? () from /usr/lib/x86_64-linux-gnu/libSDL2-2.0.so.0
#1 0x000000000040650c in sprite_free_age ()
#2 0x00000000004065f9 in AGE_SpriteLoad ()
#3 0x0000000000402740 in BattlefieldLoad () at battlefield.c:89
#4 0x0000000000402794 in BattlefieldInit (battlefield=0x1dca440, battlefieldId=1)
at battlefield.c:96
#5 0x0000000000405349 in BattleInitialize (leftTeam=0x60dff0 <leftTeam>,
rightTeam=0x60e010 <rightTeam>, battlefieldId=1) at battle.c:13
#6 0x0000000000401e8f in LoadContent () at main.c:90
#7 0x0000000000401d2b in main (argc=1, argv=0x7fffffffdfc8) at main.c:49
It crashed within SDL, and last thing that called it is sprite_free_age. What's here (AGE/AGE_Sprite.c):
void sprite_free_age(AGE_Sprite *sprite)
{
if( sprite->texture != NULL )
{
SDL_DestroyTexture( sprite->texture );
sprite->texture = NULL;
sprite->Width = 0;
sprite->Height = 0;
}
}
The only SDL call is SDL_DestroyTexture, and NULL check is performed, which means sprite have garbage data (not NULL but still not an SDL texture but rather something else). It was called from AGE_SpriteLoad:
bool AGE_SpriteLoad(AGE_Sprite *sprite, char *path)
{
sprite_free_age(sprite);
SDL_Texture *finalTexture = NULL;
SDL_Surface *loadedSurface = IMG_Load(path);
// ... the rest is omitted
So whenever you call AGE_SpriteLoad, it first tries to drop previous sprite it may've contained. It was called from BattlefieldLoad at battlefield.c:89:
void BattlefieldLoad()
{
assert(AGE_SpriteLoad(&squareWalkable, "Resources/Battlefield/SquareWalkable.png"));
assert(AGE_SpriteLoad(&squareSelected, "Resources/Battlefield/SquareSelected.png"));
assert(AGE_SpriteLoad(&squareEnemy, "Resources/Battlefield/SquareEnemy.png"));
assert(AGE_SpriteCreateBlank(&battlefieldField, LevelWidth, LevelHeight, SDL_TEXTUREACCESS_TARGET));
AGE_ListInit(&objectsList, sizeof(AGE_Sprite));
AGE_Sprite objectSprite;
int i;
char buffer[100];
for (i = 0; i < BATTLEFIELD_OBJECTS_COUNT; ++i)
{
snprintf(buffer, sizeof(buffer), "Resources/Battlefield/Object_%d.png", i+1);
AGE_SpriteLoad(&objectSprite, buffer);
AGE_ListAdd(&objectsList, &objectSprite);
}
}
Here you have uninitialised AGE_Sprite objectSprite, and you're calling AGE_SpriteLoad on it, which tries to drop old data (which is uninitialised => garbage) and (maybe) crashes. First thing coming to mind is that you need to set objectSprite to zero-bytes, either with memset or just by initialising it upon declaration, e.g. AGE_Sprite objectSprite = {};.
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....