I successfully compiled following codes, but when I tried to run the codes, a «Bus error (core dumped)» occurred every time I finished my first input of «cin >> instruct >> name >> Bal». I searched online about the bus error, but I still couldn’t find my error. Please help me with this, thanks a lot !!
// Bank.h
1 #ifndef BANK_H
2 #define BANK_H
3 using namespace std;
4
5 class BankAccount{
6 private:
7 string _name;
8 double _balance;
9
10 public:
11 BankAccount(string, double);
12 string getName();
13 void setName(string);
14 double getBalance();
15 void setBalance(double);
16 void Withdraw(double);
17 void Deposite(double);
18 void interest(int, int);
19
20 };
21 #endif
//Bank.cpp
1 #include<iostream>
2 #include<string>
3 #include "Bank.h"
4 using namespace std;
5
6 BankAccount::BankAccount(string name, double balance):_name(name),
7 _balance(balance){}
8
9 string BankAccount::getName(){ return _name;}
10
11 double BankAccount::getBalance(){ return _balance;}
12
13 void BankAccount::setName(string name){
14 _name = name;
15 return;
16 }
17
18 void BankAccount::setBalance(double balance){
19 _balance = balance;
20 return;
21 }
22
23 void BankAccount::Withdraw(double balance)
24 {
25
26 _balance = _balance - balance;
27 return;
28 }
29
30 void BankAccount::Deposite(double balance)
31 {
32
33 _balance = _balance + balance;
34 return;
35 }
36
37 void BankAccount::interest(int interestRate, int M)
38 {
39 double interest;
40
41 interest = _balance*(interestRate/1200*1.0)*M;
42 _balance = _balance + interest;
43
44 return;
45 }
//BankMain.cpp
1 #include<iostream>
2 #include<string>
3 #include "Bank.h"
4 using namespace std;
5
6 int main()
7 {
8 int x, p, check=1, i=0, j;
9 double Bal;
10 BankAccount* Account[100];
11 string name;
12 string instruct;
13
14 cin >> x >> p;
15
16 while(check)
17 {
18 cin >> instruct >> name >> Bal;
19
20 if(instruct == "Create")
21 {
22 Account[i]->setName(name);
23 Account[i]->setBalance(Bal);
24 Account[i]->interest(x, p);
25 i++;
26 }
27 else
28 {
29 if(instruct == "Withdraw")
30 {
31 for(j=0; j<i;j++)
32 {
33 if(Account[j]->getName() == name)
34 break;
35 }
36 Account[j]->Withdraw(Bal);
37
38 }
39
40 if(instruct == "Deposite")
41 {
42 for(j=0; j<i; j++)
43 {
44 if(Account[j]->getName() == name)
45 break;
46 }
47 Account[j]->Deposite(Bal);
48 }
49 }
50
51 if(instruct == "0")
52 check = 0;
53 }
54
55 cout << i;
56 for(j=0; j<i; j++)
57 {
58 cout << Account[j]->getName() << " " << Account[j]->getBalance();
59 cout << endl;
60 }
61
62 return 0;
63 }
asked Sep 13, 2015 at 11:30
2
You have many pitfalls in your code.
The first one is that you defined an array of pointers BankAccount* Account[100];
and you access it as they are initialized… Why? This array contains junk and if you need to create a new account use new BankAccount(name, balance)
first and assign it to the appropriate index in this array.
Then all your internal loops which scan for a specific name assume that this name is found and access Account[j]->...
but what if j==i
and this name
was not found?
These are the main ones that I saw.
Of course there are more but they should not cause «core dump».
Like passing string by value or dividing integer by 1200 (if that integer is smaller than 1200 you will get 0).
answered Sep 13, 2015 at 11:43
Alex Lop.Alex Lop.
6,7901 gold badge25 silver badges45 bronze badges
1
Recently wrote a linux-based logging system, encountered two errors in the middle: bus error (core dumped) and segmentation fault (core dumped). These two errors are very confusing. The error message does not explain the source code error causing these two errors. The above information does not provide information on how to find errors from the code. The clue. So it is often difficult to locate where the specific error is.
Most of the problems stem from the fact that the error is the exception detected by the operating system (OS), and this exception is reported as easy as possible on the principle of OS. The exact cause of bus errors and segmentation errors varies from OS version to OS.
These two errors occur when the OS detects a problematic memory reference. The OS communicates with it by sending a signal to the process that is in error. A signal is an event notification or a software interrupt. By default, the process dumps the information and aborts the operation after receiving a «bus error» or «segment error» signal. However, you can also set a signal handler for these signals to modify the default response of the process.
In fact, bus errors are almost always caused by unaligned reads or writes. It is called a bus error because when a misaligned memory access request occurs, the blocked component is the address bus. Alignment means that data items can only be stored on memory where the address is an integer multiple of the size of the data item. In modern computer architectures, especially RISC architectures, data alignment is required because the extra logic associated with arbitrary alignment makes the entire memory system larger and slower. By forcing each memory access to a single cache line or a separate page, hardware such as the cache controller and memory management unit (MMU) can be greatly simplified and accelerated.
We use the address alignment term to state this problem, rather than being straightforward to prohibit memory cross-page access, but they say the same thing. For example, when accessing an 8-byte double data, the address is only allowed to be an integer multiple of 8. So a double data can be stored at address 24, address 8008 or 32768, but not at address 1006 (because it cannot be divisible by 8).
The size of the page and cache are carefully designed so that an alignment rule can ensure that an atomic data item does not cross the boundaries of a page or cache block.
The book «C Expert Programming» gives an example of a bus error.
#include<stdio.h>
union {
char a[10];
int i;
} u;
int main(void)
{
#if defined(__GNUC__)
# if defined(__i386__)
/* Enable Alignment Checking on x86 */
__asm__("pushfnorl $0x40000,(%esp)npopf");
# elif defined(__x86_64__)
/* Enable Alignment Checking on x86_64 */
__asm__("pushfnorl $0x40000,(%rsp)npopf");
# endif
#endif
int *p = (int *) (&(u.a[1]));
/**
* Unaligned addresses in p will cause a bus error.
* Because the union of arrays and ints ensures that a is aligned by 4 bytes of int,
* So "a+1" is definitely not int aligned
*/
*p = 17;
printf("%d %p %p %pn", *p, &(u.a[0]), &(u.a[1]), &(u.i));
printf("%lu %lun", sizeof(char), sizeof(int));
return 0;
}
Copy code
operation result:
Bus error (core dumped)
Copy code
The assembly that starts with the condition of the main function is compiled to enable alignment of the x86 platform. The default x86 platform does not perform alignment check. If you remove that code, the executable will not report an error and the result of the operation is:
17 0x601030 0x601031 0x601030
1 4
Copy code
This is because the x86 architecture will align the addresses, access it twice, and then put the first tail and the second header together. So it creates the illusion of being misaligned and accessible.
During the test, it was found that if you add the -O3 option to gcc during the compilation process, the code will work normally.
Test environment: Ubuntu 12.04.5 LTS, x86_64, gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
2. Segment error
A segmentation error is caused by an exception to the memory management unit (MMU), which is usually caused by a pointer to an uninitialized or illegal value. This error is raised if the pointer references an address that is not in the process address space.
The book «C Expert Programming» gives the simplest example of a segmentation error.
int *p = 0;
*p = 17;
Copy code
The pointer p points to an empty address, so the assignment statement is an empty address written to 17, so a Segmentation fault is reported.
One subtlety is that causing pointers to have illegal values is usually caused by different programming errors.
A worse case is that if an uninitialized pointer happens to have a non-aligned value, it will generate a bus error instead of a segmentation fault. This is true for most architecture-based computers because the CPU first sees the address and then sends it to the MMU.
There are several direct causes of segmentation errors:
-
Refer to a pointer containing an illegal value
-
Referencing a null pointer (often due to the return of a null pointer from a function, resulting from unchecked use)
-
Access when the correct permissions are not obtained. For example, attempting to store a value into a read-only text segment causes a segmentation fault.
-
Run out of heap or stack space.
In the order of frequency of occurrence, common programming errors that can eventually lead to segmentation errors are:
-
Bad pointer value error
- If the pointer is not assigned, the memory pointed to by the pointer is referenced.
- Pass a bad pointer to the library function
- After the memory pointed to by the pointer is released, access to the memory is changed. This can be done as follows, so that if the pointer continues to be used after the pointer is released, at least the program can perform a core dump before terminating.
free(p); p = NULL; Copy code
-
Overwrite error
-
Use the pointer over the edge of the array
-
Write data outside the dynamically allocated memory, for example, dynamically allocated memory. The memory address p obtained by the user contains the data structure managed by the heap. If the value is written to the front of the address p, the heap management may be destroyed. structure. Or write the value after the address p, causing the next block of memory in the heap to be destroyed. Both of these conditions can cause internal errors in the heap.
p = malloc(256); p[-1] = 0; p[256] = 0 Copy code
-
-
Error caused by pointer release
-
Free the same piece of memory twice
-
Free block is not using memory allocated by malloc
-
Free memory still in use
-
Free an invalid pointer
For example, when iterating over a linked list like this, unpredictable results can occur when the program re-references the memory that has been freed during the next iteration of the loop.
for(p=start;p;p=p->next) free(p); Copy code
Should be introduced a tmp pointer to save.
for(p=start;p;) { tmp = p; p = p->next; free(tmp); } Copy code
-
Let me give you an example of a segmentation error I encountered:
#include <stdio.h>
#define SZ (64*1024*1024)
void func(void)
{
char buf[SZ];
printf("sizeof buf=%lun", sizeof(buf));
}
int main(void)
{
func();
return 0;
}
Copy code
This is the error that the stack space is exhausted.
In fact, the problem I encountered at the beginning was not so obvious. The space I allocated was not so large, so it was normal under normal circumstances. When my program is running, the data is getting more and more. When I exceed this SZ, I will write the data to the buf and report the error. So strictly speaking, my mistake is to destroy the stack space.
3. How to troubleshoot such a difficult mistake
This kind of error is very difficult to troubleshoot. Remember that when you didn’t have experience, you can debug it by adding printf in the source code. Now think about how inefficient this method is. If you encounter probabilistic problems, there is basically no way. After reviewing it, I realized that I fully utilized the core file. The biggest benefit of a kernel dump is the ability to save state when the problem occurs. Even if the problem is not reproduced, as long as the kernel dump is obtained, it can be debugged. Through the executable file and kernel dump, you can know the state of the process at the time, know the scene when the problem occurs, and even locate the problem statement.
Under Ubuntu, the default is to not open core dump.
3.1 Open the core file
You can view it by entering the following command at the terminal:
ulimit -c
Copy code
The display is zero, indicating that the size of the core file is limited to 0, that is, the core file is not generated.
Set the core file size to 1G blocks, which can be entered at the terminal:
ulimit -c 1073741824
Copy code
Or not limit the core file size:
ulimit -c unlimited
Copy code
3.2 Debugging via gdb
You can debug by entering the following commands in the terminal.
gdb executable-file core-file
Copy code
For example, the above example assigns a value to the empty address. When the core file is produced in the current directory, it is input at the terminal.
gdb ./a.out core
Copy code
You can get the following results
...
[New LWP 6950]
warning: Can not read pathname for load map: Input/output error.
warning: no loadable sections found in added symbol-file system-supplied DSO at 0x7ffe32533000
Core was generated by ./a.out.
Program terminated with signal 11, Segmentation fault.
#0 0x00000000004005bb in main () at segmentation_error.c:14
14 *p = 17;
(gdb)
Copy code
Very powerful, you can re-run and debug the executable, set breakpoints, and view variables, which is very convenient.
Detailed information about the core file settings, please refer toCoredump setting method。
reference:
- The C Programming Language Chinese version (2nd edition. New edition)
- «C Expert Programming»
- Ubuntu core dump setting method
What happened:
I’m getting Bus error (core dumped)
on some images after updating from 1.9 to 1.12.
Firstly, I thought it was my fault, so I completely removed kuberntes from all nodes and reinstalled it.
But it didn’t helped. I thought it was problem with shared memory. I tried to mount some volumes to /dev/shm/, but it didn’t help. On the plain docker at the same host everything works fine. Here are some images, I’ve got issue with:
postgres:9.6.5 — but I guess it’s not problem with this version (docker-library/postgres#451)
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.
The database cluster will be initialized with locale "en_US.utf8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".
Data page checksums are disabled.
fixing permissions on existing directory /var/lib/postgresql/data ... ok
creating subdirectories ... ok
selecting default max_connections ... 10
selecting default shared_buffers ... 400kB
selecting dynamic shared memory implementation ... posix
creating configuration files ... ok
Bus error (core dumped)
child process exited with exit code 135
initdb: removing contents of data directory "/var/lib/postgresql/data"
running bootstrap script ...
gitlab:gitlab/gitlab-ce:10.3.3-ce.0 — error, at the same place as in postgres, on initdb.
richarvey/nginx-php-fpm — on some images based on this it works fine, but on some not.
webdevops/php-nginx:alpine-php7 — almost like previous, but this one has auto restart, and (omg) it started on 150’th try.:
.....
2018-11-19 21:44:23,484 INFO exited: php-fpmd (terminated by SIGBUS (core dumped); not expected)
2018-11-19 21:44:24,486 INFO spawned: 'php-fpmd' with pid 348
-> Executing /opt/docker/bin/service.d/php-fpm.d//10-init.sh
2018-11-19 21:44:24,494 INFO success: php-fpmd entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
Setting php-fpm user to application
2018-11-19 21:44:24,683 INFO exited: php-fpmd (terminated by SIGBUS (core dumped); not expected)
2018-11-19 21:44:25,685 INFO spawned: 'php-fpmd' with pid 354
-> Executing /opt/docker/bin/service.d/php-fpm.d//10-init.sh
2018-11-19 21:44:25,695 INFO success: php-fpmd entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
Setting php-fpm user to application
.....
2018-11-19 21:46:28,206 INFO exited: php-fpmd (terminated by SIGBUS (core dumped); not expected)
2018-11-19 21:46:29,209 INFO spawned: 'php-fpmd' with pid 948
-> Executing /opt/docker/bin/service.d/php-fpm.d//10-init.sh
2018-11-19 21:46:29,220 INFO success: php-fpmd entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
Setting php-fpm user to application
2018-11-19 21:46:29,417 INFO exited: php-fpmd (terminated by SIGBUS (core dumped); not expected)
2018-11-19 21:46:30,418 INFO spawned: 'php-fpmd' with pid 953
-> Executing /opt/docker/bin/service.d/php-fpm.d//10-init.sh
2018-11-19 21:46:30,423 INFO success: php-fpmd entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
Setting php-fpm user to application
[19-Nov-2018 21:46:30] NOTICE: fpm is running, pid 953
[19-Nov-2018 21:46:30] NOTICE: ready to handle connections
wordpress — problem on executing php script:
/usr/local/bin/docker-entrypoint.sh: line 242: 181 Bus error (core dumped) TERM=dumb php -- <<'EOPHP'
And heres is part of the content of this file:
TERM=dumb php -- <<'EOPHP' <?php // database might not exist, so let's try creating it (just to be safe) $stderr = fopen('php://stderr', 'w'); // https://codex.wordpress.org/Editing_wp-config.php#MySQL_Alternate_Port // "hostname:port" // https://codex.wordpress.org/Editing_wp-config.php#MySQL_Sockets_or_Pipes // "hostname:unix-socket-path" list($host, $socket) = explode(':', getenv('WORDPRESS_DB_HOST'), 2); $port = 0; if (is_numeric($socket)) { $port = (int) $socket; $socket = null; } $user = getenv('WORDPRESS_DB_USER'); $pass = getenv('WORDPRESS_DB_PASSWORD'); $dbName = getenv('WORDPRESS_DB_NAME'); $maxTries = 10; do { $mysql = new mysqli($host, $user, $pass, '', $port, $socket); if ($mysql->connect_error) { fwrite($stderr, "n" . 'MySQL Connection Error: (' . $mysql->connect_errno . ') ' . $mysql->connect_error . "n"); --$maxTries; if ($maxTries <= 0) { exit(1); } sleep(3); } } while ($mysql->connect_error); if (!$mysql->query('CREATE DATABASE IF NOT EXISTS `' . $mysql->real_escape_string($dbName) . '`')) { fwrite($stderr, "n" . 'MySQL "CREATE DATABASE" Error: ' . $mysql->error . "n"); $mysql->close(); exit(1); } $mysql->close(); EOPHP fi # now that we're definitely done writing configuration, let's clear out the relevant envrionment variables (so that stray "phpinfo()" calls don't leak secrets from our code) for e in "${envs[@]}"; do unset "$e" done fi exec "$@"
What you expected to happen:
I want to get rid of Core dumped error, like it was on kubernets v1.9
How to reproduce it (as minimally and precisely as possible):
apiVersion: v1 kind: Namespace metadata: name: test --- apiVersion: v1 kind: Pod metadata: name: postgresql namespace: test labels: app: postgresql spec: nodeSelector: kubernetes.io/hostname: md2 containers: - name: postgres image: postgres:9.6.5 ports: - containerPort: 5432 hostPort: 5432 volumeMounts: - mountPath: /dev/shm name: dshm volumes: - name: dshm # hostPath: # path: /dev/shm emptyDir: medium: Medium
Anything else we need to know?:
Environment:
- Kubernetes version (use
kubectl version
):
Client Version: version.Info{Major:"1", Minor:"12", GitVersion:"v1.12.2", GitCommit:"17c77c7898218073f14c8d573582e8d2313dc740", GitTreeState:"clean", BuildDate:"2018-10-24T06:54:59Z", GoVersion:"go1.10.4", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"12", GitVersion:"v1.12.2", GitCommit:"17c77c7898218073f14c8d573582e8d2313dc740", GitTreeState:"clean", BuildDate:"2018-10-24T06:43:59Z", GoVersion:"go1.10.4", Compiler:"gc", Platform:"linux/amd64"}
- Cloud provider or hardware configuration:
Bare metal:
lshw
sudo output:
description: Rack Mount Chassis
product: ProLiant DL20 Gen9 (823556-B21)
vendor: HP
serial: CZ274504G1
width: 64 bits
capabilities: smbios-2.8 dmi-2.8 vsyscall32
configuration: boot=normal chassis=rackmount family=ProLiant sku=823556-B21 uuid=38323335-3536-435A-3237-343530344731
*-core
description: Motherboard
product: ProLiant DL20 Gen9
vendor: HP
physical id: 0
serial: CZ274504G1
*-cache:0
description: L1 cache
physical id: 0
slot: L1-Cache
size: 256KiB
capacity: 256KiB
capabilities: synchronous internal write-back unified
configuration: level=1
*-cache:1
description: L2 cache
physical id: 1
slot: L2-Cache
size: 1MiB
capacity: 1MiB
capabilities: synchronous internal varies unified
configuration: level=2
*-cache:2
description: L3 cache
physical id: 2
slot: L3-Cache
size: 8MiB
capacity: 8MiB
capabilities: synchronous internal varies unified
configuration: level=3
*-cpu
description: CPU
product: Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz
vendor: Intel Corp.
physical id: 3
bus info: cpu@0
version: Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz
serial: To Be Filled By O.E.M.
slot: Proc 1
size: 940MHz
capacity: 3900MHz
width: 64 bits
clock: 100MHz
capabilities: x86-64 fpu fpu_exception wp vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx rdseed adx smap clflushopt xsaveopt xsavec xgetbv1 dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp cpufreq
configuration: cores=4 enabledcores=4 threads=8
*-firmware
description: BIOS
vendor: HP
physical id: 4
version: U22
date: 10/02/2017
size: 64KiB
capacity: 15MiB
capabilities: pci pnp upgrade shadowing escd cdboot bootselect edd int13floppy360 int13floppy1200 int13floppy720 int5printscreen int9keyboard int14serial int17printer int10video acpi usb biosbootspecification netboot uefi
*-memory
description: System Memory
physical id: 6
slot: System board or motherboard
size: 64GiB
*-bank:0
description: DIMM Synchronous 2133 MHz (0.5 ns)
product: NOT AVAILABLE
vendor: UNKNOWN
physical id: 0
slot: PROC 1 DIMM 1
size: 16GiB
width: 64 bits
clock: 2133MHz (0.5ns)
*-bank:1
description: DIMM Synchronous 2133 MHz (0.5 ns)
product: NOT AVAILABLE
vendor: UNKNOWN
physical id: 1
slot: PROC 1 DIMM 2
size: 16GiB
width: 64 bits
clock: 2133MHz (0.5ns)
*-bank:2
description: DIMM Synchronous 2133 MHz (0.5 ns)
product: NOT AVAILABLE
vendor: UNKNOWN
physical id: 2
slot: PROC 1 DIMM 3
size: 16GiB
width: 64 bits
clock: 2133MHz (0.5ns)
*-bank:3
description: DIMM Synchronous 2133 MHz (0.5 ns)
product: NOT AVAILABLE
vendor: UNKNOWN
physical id: 3
slot: PROC 1 DIMM 4
size: 16GiB
width: 64 bits
clock: 2133MHz (0.5ns)
*-pci
description: Host bridge
product: Intel Corporation
vendor: Intel Corporation
physical id: 100
bus info: pci@0000:00:00.0
version: 05
width: 32 bits
clock: 33MHz
*-usb
description: USB controller
product: Sunrise Point-H USB 3.0 xHCI Controller
vendor: Intel Corporation
physical id: 14
bus info: pci@0000:00:14.0
version: 31
width: 64 bits
clock: 33MHz
capabilities: pm msi xhci bus_master cap_list
configuration: driver=xhci_hcd latency=0
resources: iomemory:2f0-2ef irq:27 memory:2ffff00000-2ffff0ffff
*-usbhost:0
product: xHCI Host Controller
vendor: Linux 4.4.0-104-lowlatency xhci-hcd
physical id: 0
bus info: usb@3
logical name: usb3
version: 4.04
capabilities: usb-3.00
configuration: driver=hub slots=6 speed=5000Mbit/s
*-usbhost:1
product: xHCI Host Controller
vendor: Linux 4.4.0-104-lowlatency xhci-hcd
physical id: 1
bus info: usb@2
logical name: usb2
version: 4.04
capabilities: usb-2.00
configuration: driver=hub slots=12 speed=480Mbit/s
*-usb
description: USB hub
product: Hub
vendor: Standard Microsystems Corp.
physical id: 3
bus info: usb@2:3
version: 8.01
capabilities: usb-2.00
configuration: driver=hub maxpower=2mA slots=2 speed=480Mbit/s
*-communication UNCLAIMED
description: Communication controller
product: Sunrise Point-H CSME HECI #1
vendor: Intel Corporation
physical id: 16
bus info: pci@0000:00:16.0
version: 31
width: 64 bits
clock: 33MHz
capabilities: pm msi bus_master cap_list
configuration: latency=0
resources: iomemory:2f0-2ef memory:2ffff11000-2ffff11fff
*-storage
description: SATA controller
product: Sunrise Point-H SATA controller [AHCI mode]
vendor: Intel Corporation
physical id: 17
bus info: pci@0000:00:17.0
version: 31
width: 32 bits
clock: 66MHz
capabilities: storage msi pm ahci_1.0 bus_master cap_list
configuration: driver=ahci latency=0
resources: irq:28 memory:92c80000-92c87fff memory:92c8c000-92c8c0ff ioport:2040(size=8) ioport:2048(size=4) ioport:2020(size=32) memory:92c00000-92c7ffff
*-pci:0
description: PCI bridge
product: Sunrise Point-H PCI Express Root Port #9
vendor: Intel Corporation
physical id: 1d
bus info: pci@0000:00:1d.0
version: f1
width: 32 bits
clock: 33MHz
capabilities: pci pciexpress msi pm normal_decode bus_master cap_list
configuration: driver=pcieport
resources: irq:25 ioport:1000(size=4096) memory:90000000-92afffff
*-generic:0 UNCLAIMED
description: System peripheral
product: Integrated Lights-Out Standard Slave Instrumentation & System Support
vendor: Hewlett-Packard Company
physical id: 0
bus info: pci@0000:01:00.0
version: 06
width: 32 bits
clock: 33MHz
capabilities: pm msi pciexpress bus_master cap_list
configuration: latency=0
resources: ioport:1200(size=256) memory:92a8d000-92a8d1ff ioport:1100(size=256)
*-display UNCLAIMED
description: VGA compatible controller
product: MGA G200EH
vendor: Matrox Electronics Systems Ltd.
physical id: 0.1
bus info: pci@0000:01:00.1
version: 01
width: 32 bits
clock: 33MHz
capabilities: pm msi pciexpress vga_controller bus_master cap_list
configuration: latency=0
resources: memory:91000000-91ffffff memory:92a88000-92a8bfff memory:92000000-927fffff
*-generic:1
description: System peripheral
product: Integrated Lights-Out Standard Management Processor Support and Messaging
vendor: Hewlett-Packard Company
physical id: 0.2
bus info: pci@0000:01:00.2
version: 06
width: 32 bits
clock: 33MHz
capabilities: pm msi pciexpress bus_master cap_list
configuration: driver=hpilo latency=0
resources: irq:17 ioport:1000(size=256) memory:92a8c000-92a8c0ff memory:92900000-929fffff memory:92a00000-92a7ffff memory:92a80000-92a87fff memory:92800000-928fffff
*-usb
description: USB controller
product: Integrated Lights-Out Standard Virtual USB Controller
vendor: Hewlett-Packard Company
physical id: 0.4
bus info: pci@0000:01:00.4
version: 03
width: 32 bits
clock: 33MHz
capabilities: msi pciexpress pm uhci bus_master cap_list
configuration: driver=uhci_hcd latency=0
resources: irq:17 ioport:1300(size=32)
*-usbhost
product: UHCI Host Controller
vendor: Linux 4.4.0-104-lowlatency uhci_hcd
physical id: 1
bus info: usb@1
logical name: usb1
version: 4.04
capabilities: usb-1.10
configuration: driver=hub slots=2 speed=12Mbit/s
*-pci:1
description: PCI bridge
product: Sunrise Point-H PCI Express Root Port #11
vendor: Intel Corporation
physical id: 1d.2
bus info: pci@0000:00:1d.2
version: f1
width: 32 bits
clock: 33MHz
capabilities: pci pciexpress msi pm normal_decode bus_master cap_list
configuration: driver=pcieport
resources: irq:26 memory:fe800000-fe8fffff ioport:92b00000(size=1048576)
*-network:0
description: Ethernet interface
product: NetXtreme BCM5720 Gigabit Ethernet PCIe
vendor: Broadcom Corporation
physical id: 0
bus info: pci@0000:02:00.0
logical name: eno1
version: 00
serial: ec:eb:b8:5d:5a:e8
size: 1Gbit/s
capacity: 1Gbit/s
width: 64 bits
clock: 33MHz
capabilities: pm vpd msi msix pciexpress bus_master cap_list rom ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.137 duplex=full firmware=5720-v1.39 NCSI v1.4.16.0 ip=89.184.66.47 latency=0 link=yes multicast=yes port=twisted pair speed=1Gbit/s
resources: irq:18 memory:92b30000-92b3ffff memory:92b40000-92b4ffff memory:92b50000-92b5ffff memory:fe800000-fe83ffff
*-network:1 DISABLED
description: Ethernet interface
product: NetXtreme BCM5720 Gigabit Ethernet PCIe
vendor: Broadcom Corporation
physical id: 0.1
bus info: pci@0000:02:00.1
logical name: eno2
version: 00
serial: ec:eb:b8:5d:5a:e9
capacity: 1Gbit/s
width: 64 bits
clock: 33MHz
capabilities: pm vpd msi msix pciexpress bus_master cap_list rom ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.137 firmware=5720-v1.39 NCSI v1.4.16.0 latency=0 link=no multicast=yes port=twisted pair
resources: irq:19 memory:92b00000-92b0ffff memory:92b10000-92b1ffff memory:92b20000-92b2ffff memory:fe840000-fe87ffff
*-isa
description: ISA bridge
product: Sunrise Point-H LPC Controller
vendor: Intel Corporation
physical id: 1f
bus info: pci@0000:00:1f.0
version: 31
width: 32 bits
clock: 33MHz
capabilities: isa bus_master
configuration: latency=0
*-memory UNCLAIMED
description: Memory controller
product: Sunrise Point-H PMC
vendor: Intel Corporation
physical id: 1f.2
bus info: pci@0000:00:1f.2
version: 31
width: 32 bits
clock: 33MHz (30.3ns)
capabilities: bus_master
configuration: latency=0
resources: memory:92c88000-92c8bfff
*-serial
description: SMBus
product: Sunrise Point-H SMBus
vendor: Intel Corporation
physical id: 1f.4
bus info: pci@0000:00:1f.4
version: 31
width: 64 bits
clock: 33MHz
configuration: driver=i801_smbus latency=0
resources: iomemory:2f0-2ef irq:16 memory:2ffff10000-2ffff100ff ioport:efa0(size=32)
*-scsi:0
physical id: 5
logical name: scsi0
capabilities: emulated
*-disk
description: ATA Disk
product: ST1000DM010-2EP1
vendor: Seagate
physical id: 0.0.0
bus info: scsi@0:0.0.0
logical name: /dev/sda
version: CC43
serial: Z9A8H9QD
size: 931GiB (1TB)
capabilities: partitioned partitioned:dos
configuration: ansiversion=5 logicalsectorsize=512 sectorsize=4096 signature=1bde66a3
*-volume:0
description: EXT4 volume
vendor: Linux
physical id: 1
bus info: scsi@0:0.0.0,1
logical name: /dev/sda1
version: 1.0
serial: c519e927-efc2-457b-a2b3-e9936253909d
size: 237MiB
capacity: 237MiB
capabilities: primary bootable multi journaled extended_attributes large_files huge_files dir_nlink extents ext4 ext2 initialized
configuration: created=2017-12-29 18:59:23 filesystem=ext4 modified=2017-12-29 18:59:23 state=clean
*-volume:1
description: Linux swap volume
physical id: 2
bus info: scsi@0:0.0.0,2
logical name: /dev/sda2
version: 1
serial: d3552ee3-1cf8-4af9-ab61-9d391485a57f
size: 119GiB
capacity: 119GiB
capabilities: primary multi swap initialized
configuration: filesystem=swap pagesize=4096
*-volume:2
description: EXT4 volume
vendor: Linux
physical id: 3
bus info: scsi@0:0.0.0,3
logical name: /dev/sda3
version: 1.0
serial: d34dfb91-afe5-4074-b5ce-56fd14cf7830
size: 372GiB
capacity: 372GiB
capabilities: primary multi journaled extended_attributes large_files huge_files dir_nlink extents ext4 ext2 initialized
configuration: created=2017-12-29 19:00:47 filesystem=ext4 modified=2017-12-29 19:00:47 state=clean
*-volume:3
description: EXT4 volume
vendor: Linux
physical id: 4
bus info: scsi@0:0.0.0,4
logical name: /dev/sda4
version: 1.0
serial: 0d7301bc-6882-4770-8a97-6065e504e193
size: 439GiB
capacity: 439GiB
capabilities: primary multi journaled extended_attributes large_files huge_files dir_nlink extents ext4 ext2 initialized
configuration: created=2017-12-29 19:00:49 filesystem=ext4 modified=2017-12-29 19:00:49 state=clean
*-scsi:1
physical id: 7
logical name: scsi1
capabilities: emulated
*-disk
description: ATA Disk
product: ST1000DM010-2EP1
vendor: Seagate
physical id: 0.0.0
bus info: scsi@1:0.0.0
logical name: /dev/sdb
version: CC43
serial: Z9A8D6CD
size: 931GiB (1TB)
capabilities: partitioned partitioned:dos
configuration: ansiversion=5 logicalsectorsize=512 sectorsize=4096 signature=e01a79e7
*-volume:0
description: EXT4 volume
vendor: Linux
physical id: 1
bus info: scsi@1:0.0.0,1
logical name: /dev/sdb1
version: 1.0
serial: 2af99ccb-f00f-4c0f-8eaa-ede0c4e2f769
size: 237MiB
capacity: 237MiB
capabilities: primary bootable multi journaled extended_attributes large_files huge_files dir_nlink extents ext4 ext2 initialized
configuration: created=2017-12-29 18:59:23 filesystem=ext4 modified=2017-12-29 18:59:23 state=clean
*-volume:1
description: Linux swap volume
physical id: 2
bus info: scsi@1:0.0.0,2
logical name: /dev/sdb2
version: 1
serial: 7e221fb2-312c-4af3-b7c5-5c1e26c1d3ad
size: 119GiB
capacity: 119GiB
capabilities: primary multi swap initialized
configuration: filesystem=swap pagesize=4096
*-volume:2
description: EXT4 volume
vendor: Linux
physical id: 3
bus info: scsi@1:0.0.0,3
logical name: /dev/sdb3
version: 1.0
serial: bf7c2da4-0621-46b4-9ffc-d93a446ff606
size: 372GiB
capacity: 372GiB
capabilities: primary multi journaled extended_attributes large_files huge_files dir_nlink extents ext4 ext2 initialized
configuration: created=2017-12-29 19:02:59 filesystem=ext4 modified=2017-12-29 19:02:59 state=clean
*-volume:3
description: EXT4 volume
vendor: Linux
physical id: 4
bus info: scsi@1:0.0.0,4
logical name: /dev/sdb4
version: 1.0
serial: ca144958-7752-48b4-b33a-05fac0c3dd68
size: 439GiB
capacity: 439GiB
capabilities: primary multi journaled extended_attributes large_files huge_files dir_nlink extents ext4 ext2 initialized
configuration: created=2017-12-29 19:03:01 filesystem=ext4 modified=2017-12-29 19:03:01 state=clean
*-scsi:2
physical id: 8
logical name: scsi4
capabilities: emulated
*-disk
description: ATA Disk
product: Samsung SSD 850
physical id: 0.0.0
bus info: scsi@4:0.0.0
logical name: /dev/sdc
version: 4B6Q
serial: S39KNX0J745113J
size: 238GiB (256GB)
capabilities: partitioned partitioned:dos
configuration: ansiversion=5 logicalsectorsize=512 sectorsize=512 signature=2dfc3098
*-volume
description: EXT4 volume
vendor: Linux
physical id: 1
bus info: scsi@4:0.0.0,1
logical name: /dev/sdc1
logical name: /db/ssd
version: 1.0
serial: 85e87f84-1b0b-42f9-8782-f8d09df568c2
size: 238GiB
capacity: 238GiB
capabilities: primary journaled extended_attributes large_files huge_files dir_nlink recover extents ext4 ext2 initialized
configuration: created=2017-12-29 18:59:33 filesystem=ext4 lastmountpoint=/db/ssd modified=2018-11-17 02:23:09 mount.fstype=ext4 mount.options=rw,relatime,data=ordered mounted=2018-11-17 02:23:09 state=mounted
*-power UNCLAIMED
description: Power Supply 1
vendor: HP
physical id: 1
capacity: 32768mWh
*-network
description: Ethernet interface
physical id: 2
logical name: flannel.1
serial: f6:18:0a:c3:f2:77
capabilities: ethernet physical
configuration: broadcast=yes driver=vxlan driverversion=0.1 ip=10.244.0.0 link=yes multicast=yes
- OS (e.g. from /etc/os-release):
NAME="Ubuntu"
VERSION="16.04.5 LTS (Xenial Xerus)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 16.04.5 LTS"
VERSION_ID="16.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
VERSION_CODENAME=xenial
UBUNTU_CODENAME=xenial
- Kernel (e.g.
uname -a
):
Linux md1 4.4.0-104-lowlatency Configurable restart behavior #127-Ubuntu SMP PREEMPT Mon Dec 11 13:07:12 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux - Install tools:
kubeadm - Others:
/kind bug
/sig app
/sig release
Help with mmap: Bus error (core dumped)
So, I’m working on handmade hero, and translating it to Linux, but I’m having an issue with the looped live code editing. Unfortunately, on Linux (or at least on my computer) the write
syscall isn’t really fast enough. I attempted to mmap the file, because that should be the way to write it faster, if I’m not mistaken, but I keep getting this Bus error
. My code, pulled down to as tiny as I can make it, is this:
#include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> int main(void) { int fd = open("test.txt", O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR); char *ptr = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (ptr == (char *)-1) { perror(NULL); return 1; } printf("%pn", ptr); *ptr = 'a'; munmap(ptr, 4096); }
The output is:
0x7f2b615c4000 Bus error (core dumped)
-
04-10-2010
#1
Registered User
Bus Error (Core Dumped) with sscanf
I have a C program with the following structs and main function.
Code:
struct Block { int tag; int valid; }; struct Set { struct Block *blocks; int mru; }; struct Cache { int BlockSize, NumSets, NumWays; // block size, number of sets, associativity struct Set *sets; }; struct Cache *cache_init(const char *name, const char *config) { struct Cache *c = (struct cache_t *)malloc(sizeof(struct cache_t)); if (sscanf(config, "%u:%u:%u", &c->bsize, &c->nsets, &c->nways) != 3) { fprintf(stderr, "%s configuration: none|<bsize>:<nsets>:<nways>n", name); exit(-1); } else if (c->BlockSize < 1 || !IS_POWEROF2(c->BlockSize)) { fprintf(stderr, "%s bsize (%u) must be positive and a power of 2n",name, c->BlockSize); exit(-1); } else if (c->NumSets < 1 || !IS_POWEROF2(c->NumSets)) { fprintf(stderr, "%s sets (%u) must be positive and a power of 2n", name, c->NumSets); exit(-1); } else if (c->NumWays < 1) { fprintf(stderr, "%s ways (%u) must be positiven", c->Numways); exit(-1); } return c; } int main(int argc, char **argv) { char buf[256]; FILE *f = fopen("house.trace", "r"); struct Cache *InstructionCache = NULL; struct Cache *DataCache = NULL; // check if program was called with the correct number of arguments // if not, print usage message and exit if (argc != 3) { fprintf(stderr, "usage: MyProgram none|<i-arg1>:<i-arg2>:<i-arg3> none|i|<d-arg1>:<d-arg2>:<d-arg3>n"); exit(-1); } printf("argv[0] = %sn", argv[0]) ; printf("argv[1] = %sn", argv[1]) ; printf("argv[2] = %sn", argv[2]) ; printf("strcmp(argv[1], none) = %d", strcmp(argv[1], "none")) ; if (strcmp(argv[1], "none") == 0) { icache = cache_init("icache", argv[1]); } else { InstructionCache = cache_init("icache", argv[1]) ; DataCache = cache_init("dcache", argv[2]) ; } /* More code */ }
The program gives a Bus error (core dumped) at the line:
if (sscanf(config, «%u:%u:%u», &c->bsize, &c->nsets, &c->nways) != 3)
Does anyone know how to fix this?
I thank the solver in advance.
-
04-11-2010
#2
and the Hat of Guessing
But but but … you don’t have a bsize, nsets, or nways element in your struct. Also you have a lot of Cache’s and some cache_t’s. If somehow that’s all fixed in your actual code (which I suppose it must be if it compiles?) then who knows.
-
04-11-2010
#3
Hurry Slowly
Code:
struct Cache *c = (struct cache_t *)malloc(sizeof(struct cache_t));
do not cast malloc — read FAQ
use
Code:
struct Cache *c = malloc(sizeof(*c));
to avoid mix-up of types
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
� David J. Wheeler
-
04-11-2010
#4
and the hat of int overfl
You need to post the actual code which compiles, runs and crashes.
Not some cut-down code, or worse, something recited from memory.
-
04-11-2010
#5
C++ Witch
Cut down code is fine, as long as it can be immediately tested and really demonstrates the problem.
Originally Posted by Bjarne Stroustrup (2000-10-14)
I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.
Look up a C++ Reference and learn How To Ask Questions The Smart Way
-
04-11-2010
#6
Registered User
Bus Error at scanf — Corrected code, malloc not casted but still getting error
Sorry, the correct code should be:
<code>
Sorry, the code should be:
Code:
struct Block { int tag; int valid; }; struct Set { struct Block *blocks; int mru; }; struct Cache { int BlockSize, NumSets, NumWays; // block size, number of sets, associativity struct Set *sets; }; struct Cache *cache_init(const char *name, const char *config) { struct Cache *c = (struct Cache*)malloc(sizeof(struct Cache)); if (sscanf(config, "%u:%u:%u", &c->BlockSize, &c->NumSets, &c->NumWays) != 3) { fprintf(stderr, "%s configuration: none|<BlockSize>:<NumSets>:<NumWays>n", name); exit(-1); } else if (c->BlockSize < 1 || !IS_POWEROF2(c->BlockSize)) { fprintf(stderr, "%s BlockSize (%u) must be positive and a power of 2n",name, c->BlockSize); exit(-1); } else if (c->NumSets < 1 || !IS_POWEROF2(c->NumSets)) { fprintf(stderr, "%s sets (%u) must be positive and a power of 2n", name, c->NumSets); exit(-1); } else if (c->NumWays < 1) { fprintf(stderr, "%s ways (%u) must be positiven", c->Numways); exit(-1); } return c; } int main(int argc, char **argv) { char buf[256]; FILE *f = fopen("house.trace", "r"); struct Cache *InstructionCache = NULL; struct Cache *DataCache = NULL; // check if program was called with the correct number of arguments // if not, print usage message and exit if (argc != 3) { fprintf(stderr, "usage: MyProgram none|<i-arg1>:<i-arg2>:<i-arg3> none|i|<d-arg1>:<d-arg2>:<d-arg3>n"); exit(-1); } printf("argv[0] = %sn", argv[0]) ; printf("argv[1] = %sn", argv[1]) ; printf("argv[2] = %sn", argv[2]) ; printf("strcmp(argv[1], none) = %d", strcmp(argv[1], "none")) ; if (strcmp(argv[1], "none") == 0) { icache = cache_init("icache", argv[1]); } else { InstructionCache = cache_init("icache", argv[1]) ; DataCache = cache_init("dcache", argv[2]) ; } /* More code */ }
But still giving the afore-mentioned Bus-Error.
I have tried vart’s suggestion to not cast malloc , but I still get the Bus-Error.
-
04-11-2010
#7
Registered User
Here is the gdb output.
run 4:16:2 4:16:2
Starting program: cache 4:16:2 4:16:2
HereAfter 3 arguments check.
argc = 3
argv[0] = cache
argv[1] = 4:16:2
argv[2] = 4:16:2Program received signal SIGSEGV, Segmentation fault.
0xff311678 in number () from /usr/lib/libc.so.1
-
04-11-2010
#8
and the Hat of Guessing
You need to run a backtrace (bt) to see where in your code you actually are/were to do the debugging.
-
04-11-2010
#9
Hurry Slowly
you are using %u format for reading ints — use %d,
you should check return values of malloc before using itadd printfs traces to see where your program crashes… Do you use somewhere not initialized pointer Sets?
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
� David J. Wheeler
-
04-12-2010
#10
Registered User
Apart from using %d instead of %u, it would probably help if you had an #include’d stdio.h, string.h, and stdlib.h in your source file. Without them, the compiler is making particular assumptions about the signatures of various functions which may or may not be valid.
On a quick look, the error is occurring just after printing out argv[0] — argv[2]. The output from this line
Code:
printf("strcmp(argv[1], none) = %d", strcmp(argv[1], "none")) ;
is not evident. That suggests (unless stdout is being buffered) the error is occurring earlier than the sccanf() call.
Right 98% of the time, and don’t care about the other 3%.
If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.
-
04-12-2010
#11
Registered User
Methinks! grumpy is on the right track so post the command used to invoke the program.