在 C 中动态分配的数组上调用 free() 似乎正在更改存储在另一个数组中的数据?

标签 c arrays dynamic-memory-allocation

我有以下 C 代码:

char *a, *b;
int count;
a = malloc(10);
b = malloc(10);
for(count=0;count<10;count++){
  b[count] = 'a';}
memcpy(&a, &b, 10);
for(count=0;count<10;count++){
  printf("%c %c\n", a[count], b[count]);}
free(b);
for(count=0;count<10;count++){
  printf("%c, ", a[count]);}

但是,在输出中,数组 a 的前 8 个元素似乎是通过释放 b 来删除的:

./a.out
a a
a a
a a
a a
a a
a a
a a
a a
a a
a a
, , , , , , , , a, a,

有人可以尝试解释一下这里发生了什么吗?我似乎找不到发生这种情况的原因。

最佳答案

free(b) 不是问题,该行:

memcpy(&a, &b, 10);

应该是:

memcpy(a, b, 10);

ab 已经是指向内存位置的指针,您不应该传递它们的地址,这将导致未定义的行为。

关于在 C 中动态分配的数组上调用 free() 似乎正在更改存储在另一个数组中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60353969/

相关文章:

c - 缓冲区溢出怎么写?

c - 函数指针数组错误

ios - 通过不包含字符串来过滤数组(swift 2)

javascript - 等价于 LINQ 的 Enumerable.First(predicate)

C编程,realloc后丢失数据

c - C 函数返回字符指针

c - 多边形的三角剖分

java - 查看字符是否在字符数组中的方法

从主函数调用结构值时无法打印值

c - 链表 : strange muddle of member element during output