c - SIGSEGV,(貌似)由 printf 引起

标签 c malloc printf segmentation-fault

首先,对于任何交叉发布,我们深表歉意。希望我没有在这里重复一个问题,但我无法在其他地方找到它(通过 Google 和 Stack Overflow)。

这是错误的要点。如果我在代码中的任何位置调用 printfsprintffprintf 来显示 float ,我会得到一个 SIGSEGV (EXC_BAD_ACCESS) 错误。让我举个例子。

以下抛出错误:

float f = 0.5f;
printf("%f\n",f);

这段代码不会:

float f = 0.5f;
printf("%d\n",f);

我知道那里有一个隐式转换,但我不关心那个。我只是不明白为什么打印 float 与打印整数会引发错误。

注意:部分代码使用malloc 来创建一些非常大的多维数组。但是,对于这些打印语句,这些数组不会以任何方式被引用。下面是我如何声明这些数组的示例。

#define X_LEN 20
#define XDOT_LEN 20
#define THETA_LEN 20
#define THETADOT_LEN 20
#define NUM_STATES (X_LEN+1) * (XDOT_LEN+1) * (THETA_LEN+1) * (THETADOT_LEN+1)
#define NUM_ACTS 100

float *states = (float *)malloc(NUM_STATES * sizeof(float));
// as opposed to float states[NUM_STATES] (more memory effecient)


float **q = (float**)malloc(NUM_STATES * sizeof(float*));

for(int i=0; i < NUM_STATES; i++) {
    float *a = (float*)malloc(NUM_ACTS * sizeof(float));
    for(int j=0; j < NUM_ACTS; j++) {
        a[j] = 0.0f;
    }
    q[i] = a;
}

然后上面的 printf 语句出现在代码的后面。

我包含 malloc 内容的原因是因为据我了解,SIGSEGV 与格式不正确的 malloc 调用有关。所以,如果数组初始化是导致问题的原因,我想知道:

  • 为什么?
  • 如何更改 malloc 代码来解决这个问题?

我已经包含了 OS X 生成的崩溃日志,以防万一帮助到任何人。

Process:         pole [5453]
Path:            {REDACTED}
Identifier:      pole
Version:         ??? (???)
Code Type:       X86-64 (Native)
Parent Process:  bash [5441]

Date/Time:       2009-12-08 11:38:38.358 -0600
OS Version:      Mac OS X 10.6.2 (10C540)
Report Version:  6

Interval Since Last Report:          130074 sec
Crashes Since Last Report:           68
Per-App Crashes Since Last Report:   63
Anonymous UUID:                      CA20CF15-8C46-4C85-A793-6C69F9F40140

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000100074f3b
Crashed Thread:  0  Dispatch queue: com.apple.main-thread

Thread 0 Crashed:  Dispatch queue: com.apple.main-thread
0   libSystem.B.dylib               0x00007fff828d489e __Balloc_D2A + 164
1   libSystem.B.dylib               0x00007fff828d49b8 __d2b_D2A + 45
2   libSystem.B.dylib               0x00007fff828e8c74 __dtoa + 320
3   libSystem.B.dylib               0x00007fff828aa960 __vfprintf + 4980
4   libSystem.B.dylib               0x00007fff828ec7db vfprintf_l + 111
5   libSystem.B.dylib               0x00007fff828ec75e fprintf + 196
6   pole                            0x00000001000028b5 Balance::sarsa() + 187
7   pole                            0x0000000100002e54 main + 49
8   pole                            0x00000001000010a8 start + 52

Thread 0 crashed with X86 Thread State (64-bit):
  rax: 0x0000000000000001  rbx: 0x000000010042cca0  rcx: 0x000000010042cca8  rdx: 0x0000000100074f3b
  rdi: 0x000000000000000e  rsi: 0x00007fff5fbfecbc  rbp: 0x00007fff5fbfeba0  rsp: 0x00007fff5fbfeb90
   r8: 0x00007fff5fbff0b0   r9: 0x0000000000000000  r10: 0x00000000ffffffff  r11: 0x000000010083a40b
  r12: 0x0000000000000001  r13: 0x00007fff5fbfecb8  r14: 0x00007fff5fbfecbc  r15: 0x000000010000363e
  rip: 0x00007fff828d489e  rfl: 0x0000000000010202  cr2: 0x0000000100074f3b

Binary Images:
       0x100000000 -        0x100003fff +pole ??? (???)  {REDACTED}
    0x7fff5fc00000 -     0x7fff5fc3bdef  dyld 132.1 (???)  /usr/lib/dyld
    0x7fff81697000 -     0x7fff8169bff7  libmathCommon.A.dylib ??? (???)  /usr/lib/system/libmathCommon.A.dylib
    0x7fff8289c000 -     0x7fff82a5aff7  libSystem.B.dylib ??? (???)  /usr/lib/libSystem.B.dylib
    0x7fff83c4c000 -     0x7fff83cc9fef  libstdc++.6.dylib ??? (???)  /usr/lib/libstdc++.6.dylib
    0x7fffffe00000 -     0x7fffffe01fff  libSystem.B.dylib ??? (???)  /usr/lib/libSystem.B.dylib

Model: MacBookPro4,1, BootROM MBP41.00C1.B03, 2 processors, Intel Core 2 Duo, 2.4 GHz, 2 GB, SMC 1.27f2
Graphics: NVIDIA GeForce 8600M GT, GeForce 8600M GT, PCIe, 256 MB
Memory Module: global_name
AirPort: spairport_wireless_card_type_airport_extreme (0x14E4, 0x8C), Broadcom BCM43xx 1.0 (5.10.91.19)
Bluetooth: Version 2.2.4f3, 2 service, 1 devices, 1 incoming serial ports
Network Service: AirPort, AirPort, en1
Serial ATA Device: Hitachi HTS542520K9SA00, 186.31 GB
Parallel ATA Device: MATSHITADVD-R   UJ-867
USB Device: Built-in iSight, 0x05ac  (Apple Inc.), 0x8502, 0xfd400000
USB Device: Apple Internal Keyboard / Trackpad, 0x05ac  (Apple Inc.), 0x0230, 0x5d200000
USB Device: IR Receiver, 0x05ac  (Apple Inc.), 0x8242, 0x5d100000
USB Device: BRCM2046 Hub, 0x0a5c  (Broadcom Corp.), 0x4500, 0x1a100000
USB Device: Bluetooth USB Host Controller, 0x05ac  (Apple Inc.), 0x820f, 0x1a110000

谢谢。

最佳答案

您的代码中存在与 printf 语句无关的错误。你在某处占用内存,但问题并没有显现出来,直到 printf 尝试使用 __BAlloc_D2A 分配一些内存,它崩溃了,因为它使用的堆数据结构跟踪已损坏的空闲内存块。

要尝试检测您在何处占用内存,可以使用多种工具。如果您使用的是 Linux,我建议您使用 valgrind ,它本质上是在虚拟机中运行您的代码,并在您执行任何非法操作时告诉您,例如越界读/写内存、读取未初始化的变量等。但是,它在 Mac OS X 中不可用(目前)。

一种选择是使用 libgmalloc :

% cat gmalloctest.c
#include <stdlib.h>
#include <stdio.h>

main()
{
  unsigned *buffer = (unsigned *)malloc(sizeof(unsigned) * 100);
  unsigned i;

  for (i = 0; i < 200; i++) {
    buffer[i] = i;
  }

  for (i = 0; i < 200; i++) {
     printf ("%d  ", buffer[i]);
  }
}

% cc -g -o gmalloctest gmalloctest.c
% gdb gmalloctest
Reading symbols for shared libraries .. done
(gdb) set env DYLD_INSERT_LIBRARIES /usr/lib/libgmalloc.dylib
(gdb) r
Starting program: gmalloctest
Reading symbols for shared libraries .. done
GuardMalloc: Allocations will be placed on 16 byte boundaries.
GuardMalloc:  - Some buffer overruns may not be noticed.
GuardMalloc:  - Applications using vector instructions (e.g., SSE or Altivec) should work.
GuardMalloc: GuardMalloc version 19

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0xb000d000
0x00001f65 in main () at gmalloctest.c:10
10          buffer[i] = i;
(gdb) print i
$1 = 100
(gdb) where
#0  0x00001f65 in main () at gmalloctest.c:10
(gdb)

另见 Enabling the Malloc Debugging Features .

关于c - SIGSEGV,(貌似)由 printf 引起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1868719/

相关文章:

c - `printf("%.-1s\n", "foo")` 会调用未定义的行为吗?

c - 带尾随空格的固定长度填充

C语言编程调用函数

c - 函数指针声明语法困惑

c - 将二维数组传递给 C 函数

c - 在 C 中取消分配二维数组

c - 如何检查多个 mallocs 并在出错时释放它们?

c++ - printf 对参数的顺序敏感吗?

python - bittorrent 中的 block 处理

c - 动态设置指向 int 的指针给出不正确的大小