나는 시도 malloc
에 대한 포인터 char
몇 구조에 중첩,하지만 난 코드를 실행할 때와는 main
원인이 인수를 전달합니다 seg fault
. 나는 그것이 어떻게 일어날 수 있고 왜이 seg fault
경우에 a가 발생하는지 알 수 없습니다 .
#include <stdlib.h>
typedef struct s_child t_child;
struct s_child {
char *str;
};
typedef struct s_mother t_mother;
struct s_mother {
t_child *child;
};
// int main() { // work fine
int main(int num, char **arg) { // cause a seg fault
t_mother mother;
// the malloc bellow cause a seg fault when int main() can pass arguments.
if (!(mother.child->str = (char *)malloc(sizeof(char))))
return (0);
return (0);
}
어머니를 선언했지만 자식에 대한 포인터가 초기화되지 않았습니다. 그런 다음 해당 자식 포인터를 역 참조합니다. 이것이 세그 결함의 원인입니다.
다음을 시도하십시오.
int main(int num, char **arg) { // cause a seg fault
t_mother mother;
t_child child;
mother.child = &child;
// the malloc bellow cause a seg fault when int main() can pass aguments.
if (!(mother.child->str = (char*)malloc(sizeof(char))))
return (0);
return (0);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다