Programming/C Win32 MFC2026. 1. 16. 10:44

비슷한걸 만들어 보려고 하는데 영 안되는데 신기한 옵션을 찾아서 글 써봄

의도적으로 heap을 넘기는 코드를 작성하고 free() 시에 정말 segmentation fault 가 뜨나 해보는데

$ cat t2.c 
#include <stdio.h>
#include <stdlib.h>

void main()
{
int *arr = NULL;
arr = (int*)malloc(10 * sizeof(int));
int idx = 0;
for(idx = 0; idx < 10000; idx++)
arr[idx] = idx;

printf("before\n");
fflush(stdout);

free(arr);

printf("after\n");
fflush(stdout);
}

 

아쉽게도 free가 아니라 arr[idx] 에서 범위를 넘어서 에러가 발생함

$ gcc t2.c -g
$ ./a.out 
malloc(): corrupted top size
중지됨 (코어 덤프됨)

 

fsanitize 라는 플래그를 주면 좀더 잡아 준다는데 컴파일 타임이 아니라 런타임에 작동한다.

해당 플래그를 추가하면 빌드된 용량이 증가한다.

$ gcc t2.c -g -fsanitize=address
$ ls -al
합계 40
-rwxrwxr-x  1 minimonk minimonk 23536  1월 16 10:33 a.out
-rw-rw-r--  1 minimonk minimonk   271  1월 16 10:30 t2.c

$ gcc t2.c -g
$ ls -al
합계 36
-rwxrwxr-x  1 minimonk minimonk 18704  1월 16 10:35 a.out
-rw-rw-r--  1 minimonk minimonk   271  1월 16 10:30 t2.c

[링크 :https://k0n9.tistory.com/entry/AddressSanitizer]

[링크 : https://stackoverflow.com/questions/58262749/how-to-use-gcc-with-fsanitize-address]

 

실행해서 터트리면 아래와 같이 먼가 나오는데, 엄청 컬러풀하게 터진다.

눈에 들어오는건 summay 항목의 heap-buffer-overflow

특이한게 배열 loop 돌다 터지는게 아니라 다 돌고 나서 free 가려다가 터진다. 신기하네

$ gcc t2.c -g -fsanitize=address
$ ./a.out 
=================================================================
==2713847==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x504000000038 at pc 0x609d568b42e0 bp 0x7ffdaa34e820 sp 0x7ffdaa34e810
WRITE of size 4 at 0x504000000038 thread T0
    #0 0x609d568b42df in main /home/minimonk/work/src/malloc/t2.c:9
    #1 0x7cc2e8429d8f in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
    #2 0x7cc2e8429e3f in __libc_start_main_impl ../csu/libc-start.c:392
    #3 0x609d568b41a4 in _start (/home/minimonk/work/src/malloc/a.out+0x11a4)

0x504000000038 is located 0 bytes to the right of 40-byte region [0x504000000010,0x504000000038)
allocated by thread T0 here:
    #0 0x7cc2e88b4887 in __interceptor_malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:145
    #1 0x609d568b4286 in main /home/minimonk/work/src/malloc/t2.c:7
    #2 0x7cc2e8429d8f in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58

SUMMARY: AddressSanitizer: heap-buffer-overflow /home/minimonk/work/src/malloc/t2.c:9 in main
Shadow bytes around the buggy address:
  0x0a087fff7fb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0a087fff7fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0a087fff7fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0a087fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0a087fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0a087fff8000: fa fa 00 00 00 00 00[fa]fa fa fa fa fa fa fa fa
  0x0a087fff8010: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0a087fff8020: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0a087fff8030: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0a087fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0a087fff8050: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
  Shadow gap:              cc
==2713847==ABORTING

 

idx 값을 보면 10000번 돌았는데

printf 하려고 하면 바로 malloc(): corrupted top size 하면서 터진다.

$ gdb ./a.out 
GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./a.out...
(gdb) l
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 void main()
5 {
6 int *arr = NULL;
7 arr = (int*)malloc(10 * sizeof(int));
8 int idx = 0;
9 for(idx = 0; idx < 10000; idx++)
10 arr[idx] = idx;
(gdb) l 11
6 int *arr = NULL;
7 arr = (int*)malloc(10 * sizeof(int));
8 int idx = 0;
9 for(idx = 0; idx < 10000; idx++)
10 arr[idx] = idx;
11
12 printf("before\n");
13 fflush(stdout);
14
15 free(arr);
(gdb) b 12
Breakpoint 1 at 0x1201: file t2.c, line 12.
(gdb) r
Starting program: /home/minimonk/work/src/malloc/a.out 
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Breakpoint 1, main () at t2.c:12
12 printf("before\n");
(gdb) print idx
$1 = 10000
(gdb) n
malloc(): corrupted top size

Program received signal SIGABRT, Aborted.
__pthread_kill_implementation (no_tid=0, signo=6, threadid=140737353705280) at ./nptl/pthread_kill.c:44
44 ./nptl/pthread_kill.c: 그런 파일이나 디렉터리가 없습니다.

 

그래서 printf / fflush 주석처리하고 free를 바로 브레이크 포인트 잡아서 해도 동일하게 

루프 종료되면서 바로 에러가 나는 것 같기도...

15 free(arr);
(gdb) c
Continuing.
malloc(): corrupted top size

Program received signal SIGABRT, Aborted.
__pthread_kill_implementation (no_tid=0, signo=6, threadid=140737353705280) at ./nptl/pthread_kill.c:44
44 ./nptl/pthread_kill.c: 그런 파일이나 디렉터리가 없습니다.
(gdb) 

 

'Programming > C Win32 MFC' 카테고리의 다른 글

float 자릿수 제한  (0) 2025.10.11
free(): invalid next size (normal)  (0) 2023.12.18
c에서 cpp 함수 불러오기  (0) 2023.01.04
MSB / LSB 변환  (0) 2022.08.29
kore - c restful api server  (1) 2022.07.07
Posted by 구차니
Programming/C Win32 MFC2025. 10. 11. 18:22

대부분의 경우 소수점 자리만 제한하는데

정수쪽도 길이 제한할일이 있어서 찾아보는데 묘하게 자료가 없어서 테스트 해봄

다만 리눅스에서 한거라 윈도우에서는 다를수 있음

 

void main()
{
	float a = -12.12334;
	printf("%f\n", a);
	printf("%4.1f\n",a);
	printf("%5.1f\n",a);
	printf("%6.1f\n",a);

	printf("%7.1f\n",a);
 	printf("%7.2f\n",a);
	printf("%7.3f\n",a);
   
	printf("%9.1f\n",a);
	printf("%9.2f\n",a);
	printf("%9.3f\n",a);
}

 

$ ./a.out 
-12.123340
-12.1
-12.1
 -12.1
  -12.1
 -12.12
-12.123
    -12.1
   -12.12
  -12.123

 

 

%7.1f / %7.2f / %7.3f 와

%9.1f / %9.2f / %9.3f 가

어떻게 보면 내가 하고 싶었던 결과인데 자리를 정리하면 아래와 같이 나온다.

  1 2 3 4 5 6 7 8 9
%7.3f - 1 2 . 1 2 3    
%9.3f     - 1 2 . 1 2 3

 

정리하자면

%n.mf 에서

n은 정수 부분, 소수점, 부호 를 포함한 전체 길이이고

m은 그중 소수점의 자릿수. m은 n 보다 작아야 한다.

 

'Programming > C Win32 MFC' 카테고리의 다른 글

c malloc 이후 free 시에 원인불명으로 죽는 경우  (0) 2026.01.16
free(): invalid next size (normal)  (0) 2023.12.18
c에서 cpp 함수 불러오기  (0) 2023.01.04
MSB / LSB 변환  (0) 2022.08.29
kore - c restful api server  (1) 2022.07.07
Posted by 구차니
Programming/C Win32 MFC2023. 12. 18. 17:49

또 이상한 에러가 보이길래 멘붕..

다리 다치면서 머리도 같이 다친건가 ㅠㅠ

 

free(): invalid next size (normal)
중지됨 (코어 덤프됨)

 

간단하게 malloc() 은 100 해놓고 101을 쓰면 glibc 에서 malloc 한것 이상으로 썼다고 free() 할 때 에러를 발생한다.

그냥.. 해당 메모리 번지에 접근할 때 에러내면 안되냐?

할당된 메모리를 넘어서 썼을 경우에, 해당 메모리를 해제 할때 발생
메모리를 overwrite 하는지 확인 할 것

[링크 : https://m.blog.naver.com/sysganda/30103851649]

'Programming > C Win32 MFC' 카테고리의 다른 글

c malloc 이후 free 시에 원인불명으로 죽는 경우  (0) 2026.01.16
float 자릿수 제한  (0) 2025.10.11
c에서 cpp 함수 불러오기  (0) 2023.01.04
MSB / LSB 변환  (0) 2022.08.29
kore - c restful api server  (1) 2022.07.07
Posted by 구차니
Programming/C Win32 MFC2023. 1. 4. 18:58

수정없이 사용하려면

so로 빌드하고 해당 cpp so를 호출하는 class에 속하지 않은 함수로 만들고

그걸 extern c로 불러와야 할 듯

 

[링크 : https://stackoverflow.com/questions/2744181/how-to-call-c-function-from-c]

[링크 : http://www.parashift.com/c++-faq-lite/c-calls-cpp.html]

 

[링크 : https://stackoverflow.com/questions/7281441/elegantly-call-c-from-c]

[링크 : https://5kyc1ad.tistory.com/343]

'Programming > C Win32 MFC' 카테고리의 다른 글

float 자릿수 제한  (0) 2025.10.11
free(): invalid next size (normal)  (0) 2023.12.18
MSB / LSB 변환  (0) 2022.08.29
kore - c restful api server  (1) 2022.07.07
fopen exclusivly  (0) 2021.07.09
Posted by 구차니
Programming/C Win32 MFC2022. 8. 29. 11:43

무슨 마법인진 모르겠다.

아무튼.. for  문으로 32bit를 뒤집으려면

최소한 비트 * 5 이상의 연산이 필요할텐데(쉬프트, and , or, for문 비교, for문 증가)

 

[링크 : https://stackoverflow.com/questions/746171/efficient-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c]

'Programming > C Win32 MFC' 카테고리의 다른 글

free(): invalid next size (normal)  (0) 2023.12.18
c에서 cpp 함수 불러오기  (0) 2023.01.04
kore - c restful api server  (1) 2022.07.07
fopen exclusivly  (0) 2021.07.09
vs2019 sdi , mdi 프로젝트 생성하기  (0) 2021.07.08
Posted by 구차니
Programming/C Win32 MFC2022. 7. 7. 19:08

c언어로 작성된 REST API

당연하지만(?) openSSL을 요구한다.

 

[링크 : https://choiseokwon.tistory.com/310]

[링크 : https://docs.kore.io/4.0.0/]

'Programming > C Win32 MFC' 카테고리의 다른 글

c에서 cpp 함수 불러오기  (0) 2023.01.04
MSB / LSB 변환  (0) 2022.08.29
fopen exclusivly  (0) 2021.07.09
vs2019 sdi , mdi 프로젝트 생성하기  (0) 2021.07.08
vkey win32 / linux  (0) 2021.04.30
Posted by 구차니
Programming/C Win32 MFC2021. 7. 9. 10:35

 

NOTES
   Glibc notes
       The GNU C library allows the following extensions for the string specified in mode:

       c (since glibc 2.3.3)
              Do not make the open operation, or subsequent read and write operations, thread cancellation points.  This flag is ignored for fdopen().

       e (since glibc 2.7)
              Open the file with the O_CLOEXEC flag.  See open(2) for more information.  This flag is ignored for fdopen().

       m (since glibc 2.3)
              Attempt to access the file using mmap(2), rather than I/O system calls (read(2), write(2)).  Currently, use of mmap(2) is attempted only for a file opened for reading.

       x      Open the file exclusively (like the O_EXCL flag of open(2)).  If the file already exists, fopen() fails, and sets errno to EEXIST.  This flag is ignored for fdopen().

[링크 : https://stackoverflow.com/questions/33312900/how-to-forbid-multiple-fopen-of-same-file]

[링크 : https://stackoverflow.com/questions/16806998/is-fopen-a-thread-safe-function-in-linux]

'Programming > C Win32 MFC' 카테고리의 다른 글

MSB / LSB 변환  (0) 2022.08.29
kore - c restful api server  (1) 2022.07.07
vs2019 sdi , mdi 프로젝트 생성하기  (0) 2021.07.08
vkey win32 / linux  (0) 2021.04.30
strptime  (0) 2021.02.17
Posted by 구차니
Programming/C Win32 MFC2021. 7. 8. 11:39

그냥해봤는데 내꺼에 설치된 패키지 중에는 SDI / MDI를 지원하는 패키지가 없었는지

부랴부랴 검색해서 추가중

[링크 : https://yyman.tistory.com/1357]

 

 

와와 이제 뜬다!!!!

 

흐으으으으음?! 컴파일러 뿐만 아니라 MFC 라이브러리가 별도로 필요한가?

이 프로젝트에는 MFC 라이브러리가 필요합니다. 사용되는 모든 도구 세트 및 아키텍처의 경우 Visual Studio 설치 관리자(개별 구성 요소 탭)에서 설치하세요.

[링크 : https://docs.microsoft.com/ko-kr/visualstudio/msbuild/errors/msb8041?view=vs-2019]

 

MFC로 검색해서 두개의 구성요소를 설치해야 한다.

  • 스펙터 완화를 지원하는 최신 v000 빌드 도구용 C++ MFC(x86 및 x64)
  • 최신 v000 빌드 도구용 C++ MFC(x86 및 x64)

 

스펙터는 설치안하고 최신 빌드 도구용만 까니 라이브러리 없다고 실행안되는거 보면.. 스펙터는 핑계고(?)

번역상에 문제로 스펙터 완화를 지원하는... 건 실제로는 runtime library 아닌가 의심된다.

 

아무튼 프로젝트 생성해서 빌드만 겨우 했네 휴..

근데 SDI로 작성하긴 했는데 왜이렇게 데모 프로젝트가 현란해? 무슨 Visual Studio 인 줄 ㄷㄷ

[링크 : https://yyman.tistory.com/1367]

'Programming > C Win32 MFC' 카테고리의 다른 글

kore - c restful api server  (1) 2022.07.07
fopen exclusivly  (0) 2021.07.09
vkey win32 / linux  (0) 2021.04.30
strptime  (0) 2021.02.17
while(-1) 이 될까?  (0) 2019.05.24
Posted by 구차니
Programming/C Win32 MFC2021. 4. 30. 08:35

low level 후킹으로 좌우 쉬프트 구분은 가능한 듯

 

win32

[링크 : http://stackoverflow.com/questions/1811206]

[링크 : http://stackoverflow.com/questions/3475305]

 

 

 

linux

[링크 : http://stackoverflow.com/questions/3649874]

'Programming > C Win32 MFC' 카테고리의 다른 글

fopen exclusivly  (0) 2021.07.09
vs2019 sdi , mdi 프로젝트 생성하기  (0) 2021.07.08
strptime  (0) 2021.02.17
while(-1) 이 될까?  (0) 2019.05.24
c언어용 JSON 라이브러리 목록  (0) 2018.10.23
Posted by 구차니
Programming/C Win32 MFC2021. 2. 17. 18:05

x86이나 다른데서 해봐야지.. __USE_XOPEN을 안써서 정상 작동을 안한건지

그게 아니라면 c 라이브러리를 생성할때 해당 옵션을 주고 하지 않아서 정상 작동을 하지 않은건지 모르겠다.

 

#ifdef __USE_XOPEN
/* Parse S according to FORMAT and store binary time information in TP.
   The return value is a pointer to the first unparsed character in S.  */
extern char *strptime (const char *__restrict __s,
                       const char *__restrict __fmt, struct tm *__tp)
     __THROW;
#endif

[링크 : https://stackoverflow.com/questions/3053999/c-convert-time-t-to-string-with-format-yyyy-mm-dd-hhmmss]

[링크 : https://man7.org/linux/man-pages/man3/strftime.3.html]

[링크 : https://man7.org/linux/man-pages/man3/strptime.3.html]

[링크 : https://www.it-note.kr/143]

'Programming > C Win32 MFC' 카테고리의 다른 글

vs2019 sdi , mdi 프로젝트 생성하기  (0) 2021.07.08
vkey win32 / linux  (0) 2021.04.30
while(-1) 이 될까?  (0) 2019.05.24
c언어용 JSON 라이브러리 목록  (0) 2018.10.23
uuid in c  (0) 2018.10.22
Posted by 구차니