Lea*_*oid 2 malloc free pointers
我在复制指针的内容时遇到了一些麻烦.我只想这样做:
char* vigia1;
char* vigia2;
Run Code Online (Sandbox Code Playgroud)
和..
char* aux = (char*) malloc (strlen (vigia1)+1);
aux=vigia1;
vigia1=vigia2;
vigia2=aux;
free (aux);
Run Code Online (Sandbox Code Playgroud)
vigia1,vigia2是指向char指针的指针.他们都有一个大于他们最大可能大小的malloc,这没关系.
由于我正在尝试为列表订购,我需要进行此更改以订购节点的内容.但我感到困惑:在免费(辅助)之后,vigia2没有任何价值.我想我必须将vigia2指向aux所在的内存区域,即free之后"消失"的区域.所以我该怎么做?谢谢!
指针,指针,与他们坏,更糟糕没有他们
指针是一个存储内存存储位置的数字,记住这一点,让我们深入研究你在那里所做的事情:
char* aux = (char*) malloc (strlen (vigia1)+1);
Run Code Online (Sandbox Code Playgroud)
好的,你已经在内存的一部分内部创建了一个名为heap的空间,并将新创建的内存空间的地址存储在aux中.
aux=vigia1;
Run Code Online (Sandbox Code Playgroud)
Ops,现在你已经使用存储在vigia1中的数字覆盖了你"创建"的内存空间的地址,这个数字恰好是另一个内存空间的地址.
vigia1=vigia2;
Run Code Online (Sandbox Code Playgroud)
现在你正在向vigia1发出警告值,这是另一个存储空间的另一个地址.
vigia2=aux;
Run Code Online (Sandbox Code Playgroud)
并且,在它结束时,你将vigia2指向之前由vigia1指向的内存区域.
free (aux);
Run Code Online (Sandbox Code Playgroud)
现在,你释放了aux指向的内存.等一下,在这个上面的那一行,你刚刚将vigia2指向同一个地址.难怪它没有任何用处:)
试着帮助你做你想做的事:
很久你没有任何约束要求你保留在内存中排序的列表节点,你不需要复制节点的内容,只需让第一个节点的指针指向第二个节点的内存区域节点.
一个完美的互换将是:
char *aux; // you'll need an aux to make the swap, the normal stuff
aux = vigia1; // now aux points to the same address as vigia1
vigia1 = vigia2; // vigia1 now points to the contents of vigia2
vigia2 = aux; // and now vigia2 points to the content pointed previously by vigia1
/* and tada! the swap is done :D */
Run Code Online (Sandbox Code Playgroud)