1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | /*정수 여러 개 입력받고 순서대로 출력하기*/ #include <stdio.h> #include <stdlib.h> void push(int* arr, int num, int initSize) { static int count = 0, size;//몇번 저장했는가? , 현재 저장하는 배열의 크기는? if(count == 0){ size = initSize; } if(count == size){ size += 5; arr = (int*)realloc( arr, size * sizeof(int) ); printf("fuck yeaha");//도대체 왜 안되는거야? 뭐가 문제인건데? if(arr == NULL){ printf("메모리가 ㅇ벗습니다. 어맛! 야해라"); exit(1); } } arr[count] = num; count++; } int main(){ int* inputArr;//정수들 저장하는 (동적)배열 int input, i, count; inputArr = (int*)malloc( 5 * sizeof(int) ); if(inputArr == NULL){ printf("메모리가 ㅇ벗습니다. 어맛! 야해라"); exit(1); } //입력 count = 0; while(1){ printf("원하는 정수를 입력하쇼. 근데 -1 입력하면 종료한다 "); scanf("%d", &input); //getchar(); if(input == -1){ inputArr[count] = input; break; } push( inputArr, input , 5 ); count++; } //출력 i = 0; while(inputArr[i] != -1){ printf("%d \n", inputArr[i] ); i++; } free(inputArr); return 0; } | cs |
출력
디버거가 보여준 부분
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | /*** *void __lock_fhandle(int fh) - lock file handle * *Purpose: * Assert the lock associated with the passed file handle. * *Entry: * int fh - CRT file handle * *Exit: * Returns FALSE if the attempt to initialize the lock fails. This can * only happen the first time the lock is taken, so the return status only * needs to be checked on the first such attempt, which is always in * _alloc_osfhnd (except for inherited or standard handles, and the lock * is allocated manually in _ioinit for those). * *Exceptions: * *******************************************************************************/ int __cdecl __lock_fhandle ( int fh ) { ioinfo *pio = _pioinfo(fh); int retval=TRUE; /* * Make sure the lock has been initialized. */ if ( pio->lockinitflag == 0 ) { _mlock( _LOCKTAB_LOCK ); __TRY if ( pio->lockinitflag == 0 ) { if ( !InitializeCriticalSectionAndSpinCount( &(pio->lock), _CRT_SPINCOUNT )) { /* * Failed to initialize the lock, so return failure code. */ retval=FALSE; } pio->lockinitflag++; } __FINALLY _munlock( _LOCKTAB_LOCK); __END_TRY_FINALLY } if(retval) { EnterCriticalSection( &(_pioinfo(fh)->lock) ); } // 이 스레드가 현재함수에서 반환되면 다음에 실행될 문입니다./////////////////////////////////////////// return retval; } | cs |
??
처음에 메모리를 주고 모자라면 5개씩 realloc으로 추가하는데 함수를 두번째로 호출하면 맛이 가네요
왜이럴까요....
저걸 함수로 안쓰고 그냥 할 땐 됬었는데...
함수가 아닌 main에서 코딩했을 때 성공한 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | #include <stdio.h> #include <stdlib.h> int main(){ int* inputArr;//정수들 저장하는 (동적)배열 int input, i; int count, size = 5;//몇번 저장했는가? , 현재 저장하는 배열의 크기는? inputArr = (int*)malloc( size * sizeof(int) ); if(inputArr == NULL){ printf("메모리가 ㅇ벗습니다. 어맛! 야해라"); exit(1); } //입력 count = 0; size = sizeof(inputArr); while(1){ printf("원하는 정수를 입력하쇼. 근데 -1 입력하면 종료한다 "); scanf("%d", &input); //getchar(); if(input == -1){ inputArr[count] = input; break; } if(count == size){ size += 5; inputArr = (int*)realloc( inputArr, size * sizeof(int) ); printf("---fuck yeaha---"); } inputArr[count] = input; count++; } //출력 i = 0; while(inputArr[i] != -1){ printf("%d \n", inputArr[i] ); i++; } free(inputArr); return 0; } | cs |
이부분 솔직히 잘 모르겠습니다. ...
realloc은 경우에 따라 메모리를 수평으로 늘릴 수 없으면 다른 큰 여유 공간에 메모리를 싹 copy하고 새로운 메모리 주소를 리턴하기도 함. 그래서 push 함수의 첫번째 인자는 포인터의 포인터로 넘겨주어서 새로운 포인터 값을 받아내는 구조로 해야...
디버거가 하는 말을 알아 들으려면 뭘 공부해야 될까요
"힙이 손상되어"라는 말 자체가 malloc, realloc으로 할당된 메모리가 손상되었다는 말임.
malloc, realloc, free가 할당해 주고 반환하는 메모리 영역이 힙 메모리 영역이라는 것만 알면 됨.
@ㅅㅅㅅ 흠. 그러면 아예 주소를 바꿔버렸다 그런 뜻?
ㅇㅇ. 사실 realloc에서 첫번째 인자가 NULL이면 알아서 malloc과 똑같은 효과가 나기 때문에 malloc을 처음에 해 줄 필요도 없음.
왜 주소가 바뀌냐면 5바이트짜리 메모리를 10바이트로 늘려달라고 realloc 요청했는데 그 뒤로 4바이트의 빈 공간만 있고 5바이트부턴 다른 메모리가 이미 공간을 차지하고 있다면? 이런 경우 때문에 메모리 이동이 발생할 수 있음.
호 그렇군요 ㄳㄳ
새로 할당할려면 int* 말고 int ** 로 주소를 받아야 그 주소에 할당할거임.
의도가 포인터가 다른 주소를 가리키게 할려고하는거 아닌가? 요즘 시절에 메모리 부족할리도 없을건데.. 이중 포인터 문제같은 생각이듬.
다 필요없고 realloc 쓰지마라 malloc free쓰면 윈도우 내부적으로 LFH라고 메모리 풀같은 놈이 있어서 할당 최적화 시켜주니까