Bus error core dumped c programming

bus error core dumped c programming

GNU Image Manipulation Program version 2.10.8 git-describe: GIMP_2_10_6-294-ga967e8d2c2 C compiler: FreeBSD clang version 6.0.0. For example, elements 0 to 0x1000 are inaccessible. When you try to access an inaccessible element, you generate a segmentation violation, and your program. Bus Error is caused due to alignment issues with the CPU (e.g., trying to read a long from an address which isn't a multiple of 4).

Confirm. was: Bus error core dumped c programming

Bus error core dumped c programming
Error 017 undefined symbol point

Bus error core dumped c programming - are not

C Types, Casting, Segementation Violations and Bus Errors

4 bytes for i2

Three Common Type Bugs

The first one looks idiotic, but it is at the heart of all type bugs. Look at :
main() { char c; int i; int j; i = 10000; c = i; j = c; printf("I: %d, J: %d, C: %d\n", i, j, c); printf("I: 0x%04x, J: 0x%04x, C: 0x%04x\n", i, j, c); }
Since c is a char, it cannot hold the value 10000. It will instead hold the lowest order byte of i, which is 16 (0x10). Then when you set j to c, you'll see that j becomes 16. Make sure you understand this bug.

The second bug is a typical one when you deal with math routines. If you say ``man log10,'' you'll see that it takes a double and returns a double:

double log10(double x); So tries to take the log of 100.0, which should be two:
main() { double x; x = log10(100); printf("%lf\n", x); }
When you compile it, you have to include -lm on the linking line so that it includes the math libraries. When you do this, you'll see a weird result: UNIX> pd -1035.000000 Why? This is because you didn't include math.h in your C program, and therefore the compiler assumed that you were passing log10 an integer, and that it returned an integer. And the compiler doesn't worry about casting int's to double's. So you get the bug. You can fix this by including math.h, as in :
#include < math.h > main() { double x; x = log10(100); printf("%lf\n", x); }
UNIX> pd 2.00000

Finally displays another common type bug:

main() { double x; int y; int z; x = 4000.0; y = 20; z = -17; printf("%d %d %d\n", x, y, z); printf("%f %d %d\n", x, y, z); printf("%lf %d %d\n", x, y, z); printf("%lf %lf %lf\n", x, y, z); }
UNIX> pf 1085227008 0 20 4000.000000 20 -17 4000.000000 20 -17 4000.000000 0.000000 -3566985184068214263610043868633531298423160069569428047775 20030203482592393258067630813913494098481449525958709939145371702732604277129148 77019863534390180062158966919576508126277491063615751217181296481290794579216716 39726032966871746925158515232719273883094320046823318866372976525388441556587623 1667712.000000
Typically you see the first bug in line one. You try to print out a double as an int. Not only does it get the value wrong, but it gets x and y wrong as well. You'll learn why later. Lines two and three are fine, but line 4 is now wrong, because you try to print all three quantities as double's. Again, you'll see the reason why later, but you should be aware of this kind of bug now, since you may well see it again.

Core Dump (Segmentation fault) in C/C++

Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” 

  • When a piece of code tries to do read and write operation in a read only location in memory or freed block of memory, it is known as core dump.
  • It is an error indicating memory corruption.

Common segmentation fault scenarios: 

  • Modifying a string literal : 
    The below program may crash (gives segmentation fault error) because the line *(str+1) = ā€˜nā€™ tries to write a read only memory. 











Abnormal termination of program.

Refer Storage for Strings in C for details 

  • Accessing an address that is freed : 
    Here in the below code, the pointer p is dereferenced after freeing the memory block, which is not allowed by the compiler. So it produces the error segment fault or abnormal program termination at runtime. 













Abnormal termination of program.


  • Accessing out of array index bounds : 










Abnormal termination of program.


  • Improper use of scanf() : 
    scanf() function expects address of a variable as an input. Here in this program n takes 
    value of 2 and assume it’s address as 1000. If we pass n to scanf(), input fetched from STDIN is placed in invalid memory 2 which should be 1000 instead. It’s a memory corruption leading to Segmentation fault. 








Abnormal termination of program.


  • Stack Overflow 
    It’s not a pointer related problem even code may not have single pointer. It’s because of recursive function gets called repeatedly which eats up all the stack memory resulting in stack overflow. Running out of memory on the stack is also a type of memory corruption. It can be resolved by having a base condition to return from the recursive function.
  • Dereferencing uninitialized pointer 
    A pointer must point to valid memory before accessing it. 






This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Bus Error(core dumped)

I am writing a Stack template. The stack is declared as an array.
template <typename T, size_t N>; // N is 100
class TStack
T data_1246;

I have several functions in this class template, Pop() //removes last item of stack, Push() //pushes an item to the stack, Size() //returns the size of the stack, Capacity()// returns N

I have a cpp program that tests the functionality of my template using a menu interface. When I choose Pop() without pushing anything to the stack, I get a Bus Error(core dumped).

template <typename T, size_t N>
... ::Pop()
if (size_ == 0) {std::cerr << "Stack is empty'\n'";}
else {return data_[size_-1];} //size_ is initialized to 0 and incremented when item are pushed to the stack and decremented when they are popped

When I Push() an item to the stack and then choose Pop(), it does what is expected.

What should I do to data_ to ensure that this does not happen. I understand that the Bus Error is a segmentation fault and it happens because I am trying to acces a value that is not allocated memory, but am not sure how to fix it in this situation. In the guidelines I am not allowed to use operator new or delete to insure allocation.

Thanks in advance.

Dec 22 '09


What's wrong woith the stack<> template in the C++ Standard Template Library?

Is this some sort of school assignment?

Dec 22 '09


You are using a fixed array for your stack. Not good. You should be using a linked list so you add/remove nodes as items are added or removed from the list.

In this case data_ is a T*.

When data_ is 0, the stack is empty.

A linked list will avoid the seg fault since you won't need all sorts of array management code in the class.

All you need is a linked list where you add to or remove from the end of the list.

The add is your Push(), the Remove()is your Pop().

There should be a Top() to view the top of the stack (last element in the linked list) without removing it.

Dec 22 '09

I do have a Top() function. The requirements state that I have to use an array that holds 100 elements. T data_1246 // N is passed in as 100. I just don't know why I get the seg fault because I have an if(size_ == 0) throw an error, but it seems like it throws the error AND tries to return the value when I only want it to throw the error OR return the value.

Dec 22 '09

Make one member variable for counts of push and pop operation, whenever pop calls, check that count variable, if that variable is 0 or -1, just return the pop funtion with error messsage.
When you declared that variable make it as a private.
When you decalred initially assign -1 for that member veriable.

Dec 23 '09

That's what the variable size_ takes care of, the counts of the Push() ++size_, and Pop() --size_ The only thing different would be to check for -1 also, I only check for 0. Maybe redo the if and make it:
if(size_ != 0) {return data_[size_ - 1]}
error if else

Dec 23 '09

And also, when you create the size member variable, initalize the value as 0 or -1. You can achive this using constructor .

Dec 23 '09

I initialize size_ to zero with the class constructor. I am using prefix incrementation, would this make a difference?

Dec 23 '09

I think, it will not, make any difference, better put the logs and check it.

Dec 24 '09


You haven't got an off-by-one error do you?

Your N is the number of array elements. Like 100. The array elements vary from 0 to 99.

If you use 0 to indicate the stack is empty, then when you have 1 you need to use data_[0] and not data_[1].

data_[100] is outside your array and causes a dump.

Dec 24 '09

weaknessforcats, I am now working on part 2 of my assignment. In this part, I construct a Queue. I have to use linked lists for this part. Linked lists are new to me.
template <typename T>
class TQueue
void Push (const T& t); //push t onto queue
T Pop (); //pop queue and return removed element; error if empty
T& Front (); //return front element of stack; error if empty
const T& Front () const; //const version
size_t Size () const; //return number of elements in queue
int Empty () const; //return 1 if queue is empty, 0 if not empty
void Clear (); //make the queue empty
void Display (std::ostream& os, char ofc) const; //outputs contents through os
class Link
Link (const T& t) : element_(t), nextLink_(0) {}
T element_;
Link * nextLink_;
friend class TQueue<T>;
Link * firstLink_;
Link * lastLink_;

How do I access element_ and nextLink_ in my Push function?

When I Push(t), it goes to element_, then I'm not to sure on the rest.

firstLink_ = element_;
lastLink_ = nextLink_;
nextLink_ = '\0';

Dec 27 '09

I would use two structs (classes):

1) LinkedList.
This is the linked list. Here is the address of the first element (node) and last element (Node) plus the address of the current position (used in traverses of the list:

  1. struct LinkedList
  2. {
  3.      Node* first;
  4.      Node* last;
  5.      Node* current:
  6. };

2) Node

This is an element in the list. Here is the data, and a pointer to the Node before and after this Node:

  1. struct Node
  2. {
  3.     T Data;
  4.     Node* prev;
  5.     Node* next;
  6. };

You should be able to write a series of functions:
1) Insert the second Node* argument after the first Node* argument.
This function wouldn't even know there is a list. All it does is work with the next/prev pointers to do the insert. It will be called as need by other funcitons.
2) Delete the Node that is the Node* argument.
3) Create a Node and populate with the T data argument

Then these functions that call the Node functions:

1) Append the T data to the end of the list
a) call the create node using the data
b) if the list is empty make the created node both the first and lkiat of the list
otherwise, call the insert node function using the last node as the first argunent and the new node the first argument.

The append function is called by your Queue Push().


There's a lot of info on linked list available by doing a Google.

Dec 27 '09

Unfortunately, I am unable to use anything other than what was given in the tqueue.h file provided above.

Dec 27 '09

.. ::Pop()
if (size_ == 0) {std::cerr << "Stack is empty'\n'";}
else {return data_[size_-1];} //size_ is initialized to 0 and incremented when item are pushed to the stack and decremented when they are popped

so when stack is empty, and you are calling pop..you are returning data[-1].{crossed array bounds} .Hence you are getting seg fault because of invalid memory access.


Dec 28 '09

Post your reply

Sign in to post your reply or Sign up for a free account.

UNIX for Advanced & Expert Users

10 More Discussions You Might Find Interesting

1. Programming

C: Memory Fault (core dumped)

When I run programm show this message: Memory Fault (core dumped) Does anyone can help me and tell me what is wrong? please #include <stdlib.h> #include <stdio.h> #include <process.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main(int argc, char *argv) { ... (3 Replies)

Discussion started by: ebasse2

3 Replies

3. Filesystems, Disks and Memory

(core dumped) gjar

hello, when i make gcc 4.4.2 i get this message find gnu java javax org sun -name .svn -prune -o -name '*.class' -print

What is a bus error? Is it different from a segmentation fault?

minimal POSIX 7 example

"Bus error" happens when the kernel sends to a process.

A minimal example that produces it because was forgotten:

Run with:

Tested in Ubuntu 14.04.

POSIX describes as:

Access to an undefined portion of a memory object.

The mmap spec says that:

References within the address range starting at pa and continuing for len bytes to whole pages following the end of an object shall result in delivery of a SIGBUS signal.

And says that it generates objects of size 0:

The shared memory object has a size of zero.

So at we are touching past the end of the allocated object.

Unaligned stack memory accesses in ARMv8 aarch64

This was mentioned at: What is a bus error? for SPARC, but here I will provide a more reproducible example.

All you need is a freestanding aarch64 program:

That program then raises SIGBUS on Ubuntu 18.04 aarch64, Linux kernel 4.15.0 in a ThunderX2 server machine.

Unfortunately, I can't reproduce it on QEMU v4.0.0 user mode, I'm not sure why.

The fault appears to be optional and controlled by the and fields, I have summarized the related docs a bit further here.

Program crash messages

This article/section is a stub — probably a pile of half-sorted notes, is not well-checked so may have incorrect bits.


  • segfault means the kernel says: there is something at that address, but your process may not access it
  • bus error means the kernel says: that address doesn't even exist - anymore, or at all
  • pointer bugs can lead to either segfault or bus error
...note that specific bugs are biased to cause one or the other, due to the likeliness of hitting existing versus non-existing addresses
(and various things can influence that likeliness, e.g. 32-bit address spaced usually being mostly or fully mapped, 64-bit not)
  • abort() means code itself says "okay, continuing running is a Bad Idea, let's stop now"
usually based on a test that should never fail.
if you look from a distance it's much like an exit(). The largest practical differences:
abort implies dumping core, so that you can debug this
abort avoids calling exit handlers
...and the earlier this happens, the more meaningful debugging of the dumped core is. Hence the explicit test and abort.
a fairly common case is memory allocation (as signalled by something that actually checks; not doing so is often a segfault very soon after, particularly if dereferencing null)


Segmentation refers to the fact that processes are segmented from each other.

A segmentation fault (segfault) signals that the requested memory location exists, but the process is not allowed to do what it is trying.

Which is often one of:

  • the address isn't of the requesting processess's currently mapped space, e.g.
    • a the null pointer dereference, because most OSes don't map the very start of memory to any process (mostly for this special case)
    • buffer overflow when it gets to memory outside the mapped space
    • a stack overflow can cause it (though other errors may be more likely, because depending on setup it may trample all of the heap before it does)
  • attempt to write to read-only memory

A segfault is raised by hardware that supports memory protection (the MPU in most modern computers), which is caught by the kernel.

The kernel then decides what to do, which in linux amounts to sending a signal (SIGSEGV) to the originating process, where the default signal handler quits that program.

Bus error

Means the processor / memory subsystem cannot even attempt to access the memory it was asked to access.

Also sent by hardware, received by the kernel, and on linux handled by sending it SIGBUS, triggering the default signal handler.

Possible causes include:

  • address does not make sense, in that it cannot possibly be there (outside of mappable addresses)
e.g. a using random number as a pointer pointer has a decent chance of being this or a segfault
  • IO
    • device became unavailable (verify)
    • device has to reports something is unavailable, e.g. a RAID controller refusing access to a broken drive (e.g. search for combination with "rejecting I/O to offline device")
...or ran out of space, e.g. when mmapping on a ram disk (verify)
  • address fails the platform's alignment requirements
larger-than-byte units often have to be aligned to their size, e.g. 16-bit to the nearest 16-bit address
Less likely on x86 style platforms than others (x86 is more lenient around misalignments than others)
Theoretically rare anyway, as compilers tend to pad data that is not ideally aligned.
  • cannot page in the backing memory (verify)
a broken swap device? (verify)
accessing a memory-mapped file that was removed
executing a binary image that was removed (similar note as above)

In comparison to a segfault:

  • similar in that it is about the address
and having a mangled or random-valued pointer value could lead to either
  • similar in that both are raised by the underlying hardware, that the OS sends the originating process a signal, and that the default (kernel-supplied) signal handler kills that originating process.
  • differs in that a segfault means the request is valid in a mechanical way, but the requesting process may not do this operation

Aborted (core dumped)

This message comes from the default signal handler(verify) for an incoming SIGABRT.

The reason for the handler is often to abort() and stop the process as soon as possible (without calling exit handlers(verify)), typically the process itself intentionally stopping/crashing as soon as possible, which is done for two good reasons:

  • the sooner you do, the more meaningful the core dump is to figuring out what went wrong
  • the sooner you do, the less likely you go on to nonsense things to data (and potentially write corrupted data to persistent storage)

Ideally, this is only seen during debugging, but the latter reason is why you'ld leave this in.

The likeliest sources are the process itself asking for this via a failed , from your own code or runtime checking from libraries, e.g. glibc noticing double free()s, malloc() noticing overflow corruption, etc.

On core dumps

A process core dump contains (most/all?(verify)) writeable segments specific to the process, which basically means the data segment and stack segment.

A core dump uses ELF format, though is seems to be a bit of a de facto thing wider than the ELF standard.

By default it does not contain the text segment, which contains the code, which is when debugging you also have to tell it what executable was being used.

It wouldn't be executable even them, since it's missing some details (entry point, CPU state).

Illegal instruction means the CPU got an instruction it did not support.

It can happen when executable code becoming corrupted.

More commonly, though it comes from programs being compiled with very specific optimizations within the wider platform it is part of.

Most programs are compiled to avoid this ever happening, by being conservative about what it's being run on, which is what compilers and code defaults to.

But when you e.g. compile for instructions that were recently introduced, and omit fallbacks (e.g. via intrinsics), and run it on an older CPU, you'll get this.

For example, some recent tensorflow builds just assume your CPU has AVX instructions, which didn't exist in any CPUs from before 2011[2] and still don't in some lower-end x86 CPUs (Pentium, Celeron, Atom).


Leave a Comment