讨论自动,静态和动态内存分配 i started to learn C, and i dont know why the app keeps crashing.#include <stdio.h>#include <string.h>typedef struct{ char name[50]; int age;}person;void initPerson(person *aPerson, char name[50], int age){ strcpy(aPerson->name, name); // <- causes a crash aPerson->age = age; // <- causes a crash printf("%s", aPerson->name);}int main(){ person *myPerson; initPerson(myPerson, "Oscar", 45); printf("%s, %i", myPerson->name, myPerson->age); return 0;}I have marked the lines that are causing the crash. Can someone tell me whats the problem? 解决方案 "...the app keeps crashing., ...Can someone tell me whats the problem?"Yes, your program is attempting to write to a memory location it does not own.If you must use a pointer to person, create some memory before using it:int main(){ person *myPerson = calloc(1, sizeof(*myPerson)); if(!myPerson) return 0; //test if failed initPerson(myPerson, "Oscar", 45); printf("%s, %i", myPerson->name, myPerson->age); free(myPerson);//free memory return 0;}Or, you can simply pass the address of a non-pointer instance of person (using &) to get the same results:int main(){ person myPerson = {0}; initPerson(&myPerson, "Oscar", 45); printf("%s, %i", myPerson.name, myPerson.age); return 0;}The statement:person *myPerson;Creates only an uninitialized pointer, not pointing to any particular place in memory at the time of creation. The only space used at this point is for the pointer itself, sizeof(person *). (either 4 or 8 bytes for 32bit or 64 bit target respectively.) Before a pointer variable can be used in this way, space must be dynamically allocated by a call to _void *calloc(size_t nitems, size_t size)_ or family. Memory created in this fashion sets the address of the pointer to a memory location coincident with the first byte of a contiguous block of nitems*size bytes set aside and dedicated for use with, in this case, myPerson. Memory allocated in this fashion is referred to as heap memory and must be explicitly freed with a call to free() when it is no longer needed. Generally, this method is recommended only when memory requirements for a particular variable are not known at compile timeBut the statement: person myPerson;Statically (Or automatically, depending on when/where it is created.) allocates memory with sizeof(person) bytes for an immediately usable instance of myPerson, located in memory at the address: &myPerson. Memory created in this fashion is referred to as stack memory. Because passing the address of myPerson ( &myPerson ) as an argument to initPerson(), and accomplish the same thing as was accomplished with dynamically allocated memory (discussed above), this is a much simpler option as it does not require any memory creation or freeing.Stack and heap memory explained.Discussion on automatic, static and dynamic memory allocation 这篇关于C取消引用指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 06-08 19:23