相关疑难解决方法(0)

我是否施放了malloc的结果?

这个问题,有人建议意见,我应该不会投的结果malloc,即

int *sieve = malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)

而不是:

int *sieve = (int *) malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)

为什么会这样呢?

c malloc casting

2318
推荐指数
27
解决办法
22万
查看次数

释放分配给char*的int*(由`malloc`分配)是否会调用Undefined Behavior?

标题可能令人困惑.假设str是一个分配的指针malloc.ptr类型的int*,分配给它并释放,如下面的代码片段所示:

char* str = malloc(64);
int* ptr = str;

free(ptr);
Run Code Online (Sandbox Code Playgroud)

我试图编译上面的代码.它只是发出警告:

source_file.c: In function ‘main’:
source_file.c:10:16: warning: initialization from incompatible pointer type
     int* ptr = str;
                ^
Run Code Online (Sandbox Code Playgroud)

上面的代码是否调用未定义的行为?
上面的代码片段是否释放了由mallocfor 分配的内存str

c memory free pointers undefined-behavior

7
推荐指数
1
解决办法
298
查看次数

分配给指针和free()的指针如何一起工作?

为什么释放一个指针时会说p,p也分配给另一个指针q所指向的位置,也释放q?

//for example,
int *p = malloc(sizeof(int));
*p = 10;
int *q = malloc(sizeof(int));
q = p;
free(p);
//This frees q as well.
Run Code Online (Sandbox Code Playgroud)

指针q和p具有不同的地址,但仅指向同一位置(即,它们存储的地址是10的相同地址。如果我在这里输入错误,请更正我)。

这个矛盾最明显地出现在我思考指针的方式或free()的工作方式中,因为据我所知(并不多),由于q和p具有不同的地址,释放p根本不会影响q ,除非我在理解指针上有误,否则free()/ memory以一种特殊的方式工作。

我想知道为什么会这样。(我知道该帖子释放了一个分配的指针,但是它没有解释为什么或如何发生这种情况)

c memory free pointers

6
推荐指数
1
解决办法
76
查看次数

标签 统计

c ×3

free ×2

memory ×2

pointers ×2

casting ×1

malloc ×1

undefined-behavior ×1