c++ - 使用 malloc 进行动态内存分配
问题描述
# include<stdio.h>
# include<stdlib.h>
void fun(int *a)
{
a = (int*)malloc(sizeof(int));
}
int main()
{
int *p;
fun(p);
*p = 6;
printf("%d\n",*p);
return(0);
}
为什么上面的代码无效?为什么会出现分段错误?
解决方案
因为a
本身是按值传递的,所以函数中对自身的任何修改都与参数无关。
您可以将其更改为按引用传递
void fun(int *&a)
{
a = (int*)malloc(sizeof(int));
}
顺便说一句:在 C++ 中最好使用new
(and delete
),或者不要从一开始就使用原始指针。
推荐阅读
- assembly - Verified correct shellcode segfaults when run normally; “No such file” in GDB…?
- django - django.db.utils.ProgrammingError: relation "client_apps_externalkeys" does not exist
- python - 'KMeansModel' 对象在 apache pyspark 中没有属性 'computeCost'
- postgresql - PostgreSQL Trigger on last deleted line
- mysql - Mysql - 重新排序/重置位置键
- pine-script - Tradingview - Number of Trades
- android - 如何在独立的智能手表应用程序或表盘中检查蓝牙连接手机的电池电量?
- flutter - How to show Snackbar at the bottom of container and not screen flutter
- kdb - 使用 -11!(-2;`:tplog) 在 tplog 行计数期间报告进度
- javascript - OnClick violating Content Security Policy