C语言 Malloc 返回同一指针两次



我在main中分配动态数组,如下所示:

char *arr = malloc(sizeof(char));

然后在一个随机函数中,我将该数组重新分配给 n 个元素,例如:

arr = realloc(arr, n * sizeof(char));

然后我对数组做了一个随机的东西,在另一个函数中,我想再分配一个包含 n 个元素的数组,如下所示:

char *arr2 = malloc(n * sizeof(char));

但是这个 malloc 返回的地址与 arr 相同。我尝试了所有方法,但仍然返回相同的地址,因此 arr2 指向 arr。我做错了什么? 如果我再次分配新数组,让我们使用相同的方法说 arr3,现在它可以工作并且它给了我新的地址。

编辑:

void reallocate(char *arr, int newLength) {
arr = realloc(arr, newLength * sizeof(char));
}
void fc1 (char *arr, int *length) {
char *temp = malloc(*length * sizeof(char));
strcpy(temp, arr);
int d;
scanf("%d", &d);
char *arr2 = malloc(d * sizeof(char)); //there it gives me the same adress 
scanf("%s", arr2);
}
int main(void) {
char arr = malloc(sizeof(char));
int *length = malloc(sizeof(int));
*length = 10;
reallocate(arr, 10);
fc1(arr, length);
return 0;
}

我们需要查看代码才能确定,但有两种方式可以发生:

void func2(char *s)
{
do_something(s);
free(s); // we are done with it
}
void func1(void)
{
char * array = some_func();
func2(array); // Oops, func2 frees it
char * array2= malloc (...); // could get the same pointer
}

在这里,func1将指针传递给func2从而释放它。对于func1来说,在该点之后对array执行任何操作都是错误的,因为它可以重新分配。

第二种方式:

void get_data(char *s)
{
char *data = // code to get some data from somewhere
s = realloc (s, strlen(data) + 1);
strcpy(s, data);
}
void func1(void)
{
char *ptr = malloc(12);
get_data(ptr);
// oops, ptr has the old value
char *ptr2 = malloc(12); // could get the same pointer
}

在这里,get_data调用realloc但调用方仍然具有realloc可能释放的旧指针。

但是我们需要查看代码才能确定。

更新

我猜对了。这是我上面示例中的第二种方式:

void reallocate(char *arr, int newLength) {
arr = realloc(arr, newLength * sizeof(char));
}

这看起来与我上面的get_data函数一模一样。此函数不会将arr的新值传递回调用方,因此调用方仍具有可以释放的旧值。

reallocate(arr, 10);
fc1(arr, length);

这看起来与我上面的第二func1一模一样。您将arr传递给reallocate这可能会使其无效,但随后您将旧的值arr传递给fc1。但reallocate可能已经释放了它。返回新值是有原因的reallocreallocate函数没有。

最新更新