나는 다음과 같은 코드를 가지고 :realloc은 메모리를 확장하거나 메모리 문제를 일으킬 수 있습니까?
는 출력#include <stdio.h>
#include <stdlib.h>
#define OUT
void getDataFromServer(OUT int** array, OUT int* size)
{
static int tmpArr[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F};
*size = sizeof tmpArr/sizeof(int);
printf("Before realloc: %p\n", *array);
*array = realloc(*array, sizeof(*array) * *size);
printf("After realloc : %p\n", *array);
int i=0;
for (; i < *size; i++)
{
(*array)[i] = tmpArr[i];
}
}
int main(void)
{
int size = 0;
int* dataFromServer = malloc(sizeof *dataFromServer);
printf("in main: %p\n", dataFromServer);
getDataFromServer(&dataFromServer, &size);
int x;
for (x=0; x < size; x++)
printf("%d ", dataFromServer[x]);
printf("\n\n");
free(dataFromServer);
return 0;
}
: 출력에서
in main: 003F1708
Before realloc: 003F1708
After realloc : 003F3430
0 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
에서, realloc
새로운 메모리 주소에 대한 포인터를 반환 ..
malloc
으로 생성 된 위치를 해제하는 대신에?
위 코드에서 원하는 것은 무엇입니까? Just expand the memory location reserved previously
?
감사합니다.
EDIT
: 사실, 아래의 각 답변은 저에게 귀중한 정보를 제공했습니다. 그리고 받아들이기만 한 응답을 선택해야하기 때문입니다. 위의 코드를 수정 한 코드를 선택했습니다!
당신은 더 나은 성공적인 realloc을 한 후 그것을 해제하지 않는 게 좋을() – wildplasser
@wildplasser : 당신은 당신이해야 더 이상 필요하지 않을 때; 나는 그'/ * ... * /'를 분명히 할 것이다. –
알지만, 초보자를 혼란스럽게 할 수 있습니다. 이 쓰레드는 사용 후 free() 메모리가 아니라 realloc()에 관한 쓰레드이다. – wildplasser