函数内部的重新分配不如预期般工作

huangapple go评论89阅读模式
英文:

Realloc inside function doesn't work as expected

问题

我正在处理一个程序,成功地隔离了不工作的部分,但我无法弄清楚为什么它不起作用。
函数内的realloc应该重新分配数组元素,但有时地址相同,有时只是0,这导致代码内部出现错误并崩溃。

int main() {
    char *string = (char*) malloc(sizeof(char));
    resizeString(&string);
    free(string);
    return 0;
}

void resizeString(char* *string) {
    int q;
    *string = realloc(*string, 5 * sizeof(char));
    for (q = 0; q < 5; q++) {
        printf("0x%p ", &(*string)[q]);
    }
    printf("\n");
}

函数内部的重新分配不如预期般工作

英文:

I am working on a program and I successfully isolated the non-working part, but I can't figure out why this does not work.
The realloc inside the function shold reallocate the array elements but sometimes the addresses are the same and sometimes they are just 0, which causes errors inside the code and crashes

int main() {
    char *string = (char*) malloc(sizeof(char));
    resizeString(&amp;string);
    free(string)
    return 0;
}

void resizeString(char* *string) {
	int q;
	*string = realloc(*string, 5 * sizeof(char));
	for (q = 0; q &lt; 5; q++) {
		printf(&quot;0x%p &quot;, &amp;*string[q]);
	}
    printf(&quot;\n&quot;);
}

函数内部的重新分配不如预期般工作

答案1

得分: 3

你需要在正确的地方添加括号,以正确打印数组元素的地址。

```c
        printf("%p ", &(*string)[q]);

这将正确打印连续的地址:

0x6000013dc040 0x6000013dc041 0x6000013dc042 0x6000013dc043 0x6000013dc044 

这与realloc()无关,如果最初分配了5个字符,你仍然会遇到相同的问题。

在格式字符串中也不需要写0x;大多数C库会自动显示该前缀作为%p格式的一部分。


<details>
<summary>英文:</summary>

You need to add parentheses to print the addresses of the array elements properly.

    printf(&quot;%p &quot;, &amp;(*string)[q]);
This correctly prints consecutive addresses:
```none
0x6000013dc040 0x6000013dc041 0x6000013dc042 0x6000013dc043 0x6000013dc044 

This has nothing to do with realloc(), you'd have the same problem if you allocated 5 characters originally.

There's also no need to write 0x in the format string; most C libraries show that prefix automatically as part of %p format.

答案2

得分: 1

The realloc()函数在你的代码中基本上是有效的,但存在另外两个问题:

  1. 你的初始单字符分配从未初始化(因此在realloc()调用之前或之后将有哪个字符在其中是不确定的)。

  2. 你用于打印出realloc()后数组中的字符的代码是错误的(它试图打印出指针,而不是字符,这是没有意义的)。

以下是一个更新后的代码版本,它执行了你期望的操作(请注意,我在main()中初始化了原始字符为X,即0x58,以便我们可以在realloc()发生后验证它仍然设置为该值):

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void resizeString(char* *string) {
    int q;

    char * s = (char *) realloc(*string, 5 * sizeof(char));
    for (q = 0; q < 5; q++) {
        printf("0x%x ", s[q]);
    }
    printf("\n");

    *string = s;  // 更新调用代码的指针以指向新的缓冲区位置
}

int main() {
   char *string = (char*) malloc(sizeof(char));
   *string = 'X';

   resizeString(&string);
   free(string);
   return 0;
}

运行上面的代码会产生以下输出:

0x58 0x0 0x0 0x0 0x0 
英文:

The realloc() call in your code is basically working, but there are two other problems:

  1. Your initial one-char allocation is never initialized (so it's indeterminate what character will be in it before or after the realloc() call)

  2. Your code to print out the characters in the post-realloc() array is wrong (it's trying to print out pointers, not characters, which doesn't make sense).

Here's an updated version of the code that does what you'd expect (note that I've initialized the original char to X aka 0x58 in main() so that we can verify that it is still set to that value after the realloc occurs)

#include &lt;string.h&gt;
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

void resizeString(char* *string) {
    int q;

    char * s = (char *) realloc(*string, 5 * sizeof(char));
    for (q = 0; q &lt; 5; q++) {
        printf(&quot;0x%x &quot;, s[q]);
    }
    printf(&quot;\n&quot;);

    *string = s;  // update calling code&#39;s pointer to the new buffer location
}

int main() {
   char *string = (char*) malloc(sizeof(char));
   *string = &#39;X&#39;;

   resizeString(&amp;string);
   free(string);
   return 0;
}

... running the above gives this output:

0x58 0x0 0x0 0x0 0x0 

huangapple
  • 本文由 发表于 2023年6月22日 08:38:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527965.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定