문자열에 메모리를 동적으로 할당하려고 시도하지만 크기를 인쇄 할 때 할당해야하는 (11 + 1) 바이트 대신 4를 표시합니다. 왜 이런 일이 생길까요? 문자열이 잘 인쇄됩니다.문자열에 대한 동적 메모리 할당이 올바르지 않습니다.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char c, *string;
int i=0, a=1;
printf("\nEnter the string : ");
string = (char *) malloc (sizeof(char));
while(c != '\n'){
c = getchar();
string = (char *) realloc (string, sizeof(char) * a);
string[i] = c;
a++, i++;
}
string[i] = '\0';
puts(string);
printf("\n%d", sizeof(string));
}
Input : Sample Text
Output :
Sample Text
4
'sizeof (string)'대신'strlen (string)'을 사용합니다. 후자는 char *에 포인터를 저장하는 데 필요한 메모리를 제공합니다. 또한,'strlen' 또는'sizeof'에 의해 주어진 숫자에 대한 적절한 형식 지정자는'% zu'입니다. –
몇 가지 : 먼저 [malloc (및 친구들)을 캐스팅하는 것에 관한이 토론] (http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)을 읽어보십시오. 둘째, ['realloc'] (http://en.cppreference.com/w/c/memory/realloc)을 사용할 때 함수에 전달하는 포인터를 직접 할당하지 말고 [' realloc'] (http://en.cppreference.com/w/c/memory/realloc)는 널 포인터를 반환합니다. 셋째, 터미네이터 공간을 할당하지 않습니다. 넷째, 마지막 문자를 종결 자로 덮어 씁니다. –
버그 :'string [i] = '\ 0'; '그러나'string + i'는 존재하지 않습니다 (할당 된 저장소가 없습니다). –