我正在编写一个简单的程序,以确保我在学习哈佛大学的CS50课程时充分理解C语言中指针的工作原理。以下是代码:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *a = malloc(sizeof(int));
*a = 5;
printf("the address of pointer a is: %p\n", &a);
printf("the address that a is pointing to is: %p\n", a);
printf("the contents of a are: %i\n", *a);
printf("please enter a new value for a: \n");
scanf("%i", a);
printf("the address of pointer a is: %p\n", &a);
printf("the address that a is pointing to is: %p\n", a);
printf("the contents of a are: %i\n", *a);
int *b = malloc(sizeof(int));
*b = 7;
printf("the address of pointer b is: %p\n", &b);
printf("the address that b is pointing to is: %p\n", b);
printf("the contents of b are: %i\n", *b);
a = b;
printf("setting a = b\n");
printf("the address of pointer a is: %p\n", &a);
printf("the address that a is pointing to is: %p\n", a);
printf("the contents of a are: %i\n", *a);
free(a);
free(b);
}
代码编译没有问题,但执行时出现以下错误:"* Error in `./address': double free or corruption (fasttop): 0x00000000018b7030 * Aborted"
如果我删除free(a)或free(b)语句之一,则此问题消失,但valgrind显示存在内存泄漏: "==9626== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==9626== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==9626== by 0x4206AD: main (address.c:6)"
我查看了其他问题和提到double free corruption的其他网站,但仍然找不出问题所在... 我感觉答案很简单,问题可能在于"a = b"语句,但我真的不明白为什么一个指针不能指向另一个指针所指向的内存位置,然后释放两个指针占用的内存...
a = b;
,而是*a = *b;
— 这两者有很大的区别,而第二种写法(带有*
)不会引起问题。它将b
指向的值分配给a
指向的内存。 - Jonathan Lefflergcc
,至少使用:-Wall -Wextra -pedantic -Wconversion -std=gnu17
)请注意,其他编译器具有执行相同功能的不同选项。 - user3629249printf()
调用中的2个输出警告。这(可能)不会阻止代码正常工作,但它肯定不是没有问题的代码。 - user3629249malloc
、calloc
、realloc
)时,始终检查返回的值是否为(!=NULL),以确保操作成功。 - user3629249-std=gnu17
更改为-std=gnu11
,因为 C17 标准尚未在所有地方(包括现在)得到支持。 - user3629249