2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mistake > char str[] と extern char *str;

Last updated at Posted at 2015-06-20

引用: C++プログラミングの落とし穴 by Steve Oualline

sub.cpp
char str[] = "Hello World";
main.cpp
# include <iostream>

extern char *str;

int main()
{
    std::cout << str << std::endl;
    return (0);
}

CentOS6.5で上記cppをコンパイル・実行すると「Segmentation fault(core dumped)」になる。

何故か?

strの定義がchar []とchar *で異なるからということらしい。

プログラムmain()はstrが文字ポインタであると考え、アドレスを期待してその場所から最初の4バイトを読み取る。最初の4バイトは「Hell」であり、それはアドレスではないのでプログラムはクラッシュする。


こういうミスもあるためか、コーディング規約では以下のようにしているものもある。 (引用: 組込みソフトウェアの開発向けコーディング作法ガイド C++言語版])
R3.1.1 (1)配列のextern宣言では要素数を必ず指定する。

上記の場合は

extern char str[12];

にするのだろう。

ただし、Hellow Worldという文字を変更した時、12というサイズを変更する必要があり、その変更忘れというミスを誘発するかもしれない。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?