없음, 당신이 수를 change.kj하지 않았다하지 못하기 때문에 내가 뭔가를 생각하고
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct hello {
char *before;
char *message;
char *after;
};
int main(){
struct hello there= {
"Before",
"Hello",
"After",
};
printf("%ld\n", strlen(there.message));
printf("%s\n", there.message);
printf("%d\n", sizeof(there));
there.message = malloc(20 * sizeof(char));
there.message = "Hello, there!";
printf("%ld\n", strlen(there.message));
printf("%s\n", there.message);
printf("%s %s\n", there.before, there.after);
printf("%d\n", sizeof(there));
return 0;
}
입니다 런타임시이를 감지하려면 valgrind을 사용하십시오 (Linux의 경우).
당신은 코딩 :
there.message = malloc(20 * sizeof(char));
there.message = "Hello, there!";
첫 번째 과제 호출 malloc(3)을. 첫째, malloc
을 호출 할 때 항상 실패하는지 테스트해야합니다. 그러나 실제로 그것은 일반적으로 성공합니다. 그래서 더 나은 코드를 적어도 :
there.message = malloc(20 * sizeof(char));
if (!there.message)
{ perror("malloc of 20 failed"); exit (EXIT_FAILURE); }
두 번째 과제는 같은 포인터 there.message
에 상수 리터럴 문자열 "Hello, there!"
의 주소를 넣어, 당신은 첫 번째 값을 잃었다. 당신은 아마 상수 문자열
strncpy (there.message, "Hello, there!", 20*sizeof(char));
은 (방금 strcpy(3)를 사용하지만 버퍼 오버 플로우 조심 수) 것을 복사 할
당신은 strdup(3) (그리고 GNU libc의를 사용하여 일부 문자열 (힙) 새 복사본을 얻을 수 마침내
there.message = strdup("Hello, There");
if (!there.message)
{ perror("strdup failed"); exit (EXIT_FAILURE); };
) ... 또한 asprintf(3)있다, 그것은 힙 메모리를 종료 프로그램에서 free
좋은 맛입니다. (그러나 운영 체제 _exit(2) 시간에 프로세스 공간을 supress 것이다.
이
더 읽기에 대한 C 프로그래밍, memory management, garbage collection.입니다 아마 Boehm's conservative GC
AC 포인터를 사용하는 것을 고려 그냥 메모리 주소 영역. 응용 프로그램이 필요로하는
추신 : 노련한 베테랑 프로그래머라도 C의 수동 메모리 관리는 까다 롭습니다.
내 아 ... "24 시간 자신에게 C를 가르쳐". [C 태그 위키] (http://stackoverflow.com/tags/c/info)에 책 목록이 있습니다. X 일/시간/분으로 C를 가르치는 광고에서 벗어나십시오. – Mat
내가 24 시간 만에 로켓 발사를 배울 수 있다면 !! –
@narnie 서둘러주세요. 종말이 내일 저녁이라도 정말로 소중히하는 기억. –