free() :无效指针以及如何重用当前释放的指针
free() : invalid pointer and how to reuse a currently freed pointer
我想将我的指针指向另一个对象并释放前一个对象的内存。这就是我所做的,但我有一个无效的指针错误。正确的做法是什么?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int number = 5;
int number2 = 10;
// Give memory manually
int *pointer2number = (int *) malloc(sizeof(int));
pointer2number = &number;
printf("Number is %i\n", number);
printf("Address of number is %p\n", pointer2number);
// Free memory
free(pointer2number);
pointer2number = (int *) malloc(sizeof(int));
pointer2number = &number2;
printf("New number is %i\n", *pointer2number);
return 0;
}
int *pointer2number = (int *) malloc(sizeof(int));
pointer2number = &number;
你将number
的地址赋值给指针pointer2number
,并用它替换之前存储在pointer2number
中的已分配动态内存的地址。
第二次尝试 number2
也是如此。
任何尝试 free()
之前未由内存管理函数分配的内存,都会调用未定义的行为:
"The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined."
Source: ISO/IEC 9899:2018 (C18), Section 7.22.3.3/2
作为副作用,之前分配的动态内存也不会 free()
。
想多了你程序的逻辑!
我想将我的指针指向另一个对象并释放前一个对象的内存。这就是我所做的,但我有一个无效的指针错误。正确的做法是什么?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int number = 5;
int number2 = 10;
// Give memory manually
int *pointer2number = (int *) malloc(sizeof(int));
pointer2number = &number;
printf("Number is %i\n", number);
printf("Address of number is %p\n", pointer2number);
// Free memory
free(pointer2number);
pointer2number = (int *) malloc(sizeof(int));
pointer2number = &number2;
printf("New number is %i\n", *pointer2number);
return 0;
}
int *pointer2number = (int *) malloc(sizeof(int));
pointer2number = &number;
你将number
的地址赋值给指针pointer2number
,并用它替换之前存储在pointer2number
中的已分配动态内存的地址。
第二次尝试 number2
也是如此。
任何尝试 free()
之前未由内存管理函数分配的内存,都会调用未定义的行为:
"The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined."
Source: ISO/IEC 9899:2018 (C18), Section 7.22.3.3/2
作为副作用,之前分配的动态内存也不会 free()
。
想多了你程序的逻辑!