Error
Runtime Error: Segmentation fault
Explain
Segmentation fault: Segment error, check if there is an array out of bounds, pointer exception, access to memory area that should not be accessed.
๋ฐฐ์ด ๋ฒ์๋ฅผ ๋ฒ์ด๋ ๊ฒฝ์ฐ(an array out of bounds)
null object๋ฅผ ์ฌ์ฉํ๋ ค๊ณ ํ ๊ฒฝ์ฐ(pointer exception)
์ ๊ทผํ ์ ์๋ ๋ฉ๋ชจ๋ฆฌ ์์ญ์ ์ฐธ์กฐํ๋ ค๋ ๊ฒฝ์ฐ(access to memory area that should not be accessed)
์ฆ, Segmentation fault๋ ์๋ชป๋ ๋ฉ๋ชจ๋ฆฌ ์ฐธ์กฐ ๋๋ฌธ์ ๋ฐ์ํฉ๋๋ค. ์ฌ๊ธฐ์ ์๋ชป๋ ๋ฉ๋ชจ๋ฆฌ ์ฐธ์กฐ๋ ์๋์ ๊ฐ์ ๊ฒฝ์ฐ๊ฐ ์์ต๋๋ค.
1. null ๊ฐ์ ๊ฐ๋ฆฌํค๋ ํฌ์ธํฐ์ ์ ๊ทผํ ๊ฒฝ์ฐ
2. ํ ๋น๋ฐ์ ๋ฉ๋ชจ๋ฆฌ ๊ณต๊ฐ์ ๋์ ๊ณณ์ ๊ฑด๋๋ฆฐ ๊ฒฝ์ฐ
3. ์กด์ฌํ์ง ์๋ ๋ฉ๋ชจ๋ฆฌ ์์ญ์ ๊ฐ๋ฆฌํฌ ๊ฒฝ์ฐ
4. read-only ํ์ ๋ฉ๋ชจ๋ฆฌ ์์ญ์ ์ฐ๋ ค๊ณ ํ ๊ฒฝ์ฐ
์์ ๊ฐ์ด ํ์ฉ๋์ง ์์ ๋ฐฉ๋ฒ์ผ๋ก ๋ฉ๋ชจ๋ฆฌ์ ์ ๊ทผํ๋ฉด ๋ฉ๋ชจ๋ฆฌ๊ฐ ์ค์ผ๋ ์ ์๋ ์ํ์ด ์์ต๋๋ค. ์ด๋ฌํ ์ํ์ ๋ฐฉ์งํ๊ธฐ ์ํด ๋ฉ๋ชจ๋ฆฌ ๋ฒ๊ทธ๋ฅผ ์๋ ค์ฃผ๋ ์๋ฌ์ฝ๋์ ๋๋ค.
Solution
์๋์ ๊ฐ์ด ์ฝ๋๋ฅผ ์์ฑํ์ ๋ Segmentation fault ์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค. ์์ธ์ scanf์์ weight1, weight2๋ฅผ ์ ๋ ฅํ ๋ '&'๋ฅผ ์ฌ์ฉํ์ง ์์๊ธฐ ๋๋ฌธ์ ๋๋ค. &์ ํด๋น ๋ณ์์ ์ฃผ์๋ฅผ ๊ฐ๋ฆฌํค๋ ์ญํ ์ ํฉ๋๋ค. ๋ฐ๋ผ์ &๋ฅผ ์ฐ์ง ์๊ณ weight1, weight2 ๋ณ์์ ์ ๋ ฅ๋ ๊ฐ์ ํ ๋นํ๋ ค๊ณ ํ๋ฉด ์ ํํ ๋ฉ๋ชจ๋ฆฌ ์ฃผ์๋ฅผ ์ฐพ์ง ๋ชปํด ์๋ฌ๊ฐ ๋ฐ์ํ๊ฒ ๋ฉ๋๋ค. ๋ฐ๋ผ์ weight1์ &weight1, weight2๋ฅผ &weight2๋ก ๋ฐ๊ฟ์ฃผ๋ฉด ์๋ฌ๋ฅผ ํด๊ฒฐํ ์ ์์ต๋๋ค.
<Before>
#include <stdio.h>
int main()
{
int height1, weight1, height2, weight2;
scanf("%d %d", &height1, weight1);
scanf("%d %d", &height2, weight2);
printf("%d", height1 > height2 && weight1 > weight2);
return 0;
}
<After>
#include <stdio.h>
int main()
{
int height1, weight1, height2, weight2;
scanf("%d %d", &height1, &weight1);
scanf("%d %d", &height2, &weight2);
printf("%d", height1 > height2 && weight1 > weight2);
return 0;
}
์ด ์๋ฌ ๋๋ถ์ scanf๋ฅผ ์จ์ ๋ณ์๋ฅผ ํ ๋นํ๊ธฐ ์ํด์๋ ๊ผญ '&'๋ฅผ ์จ์ค์ผ ํจ์ ๋ค์ ํ ๋ฒ ๋ณต์ตํ ์ ์์์ต๋๋ค.
Reference
[์ค๋ฅ] segmentation fault ์์ธ
โ segmentation fault๋? - ์๋ชป๋ ๋ฉ๋ชจ๋ฆฌ ์ฐธ์กฐ ๋๋ฌธ์ ๋ฐ์, ์ฆ, ๊ฑด๋๋ฆฌ์ง ๋ง์์ผ ํ ๊ณณ์ ๊ฑด๋๋ ธ๊ธฐ ๋๋ฌธ์ ๋ฐ์ํ๋ ์๋ฌ. - ์ด๋ค ํ๋ก๊ทธ๋จ์ด ์์ ์ด ์ด์์ฒด์ ๋ก๋ถํฐ ๋ฐฐ์ ๋ฐ์ง ๋ชปํ ์์ญ(๋ฉ๋ชจ๋ฆฌ)์
codingfriend.tistory.com
'EIF' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
EIF 3: ERR_HTTP_HEADERS_SENT (0) | 2021.12.05 |
---|---|
EIF 2: First Project (2) - try, catch ์๋ฌ (0) | 2021.11.24 |
EIF 1: First Project (1) - AWS ๋ฐฐํฌ ๋ฐ Cloudfront Cache ์ญ์ (0) | 2021.11.22 |