Sto*_*ent 1 c valgrind memory-management
也许我太忙于测试我的作业,但这是我的困境:
这是我的冒犯功能(或多或少):
struct thing{
char* data;
}
int function(struct thing* arg){
if(arg->data == NULL)
return -1;
}
Run Code Online (Sandbox Code Playgroud)
这是我的冒犯性输入:
struct thing *x = malloc(sizeof(struct thing));
function(x);
Run Code Online (Sandbox Code Playgroud)
当我测试它时,valgrind 会输出这个:
struct thing{
char* data;
}
int function(struct thing* arg){
if(arg->data == NULL)
return -1;
}
Run Code Online (Sandbox Code Playgroud)
我大约 99% 确定这是因为 valgrindx->data在尚未初始化NULL或分配时存在评估问题。有解决方法吗?
我认为 valgrind 在这里抱怨是正确的,因为data实际上没有初始化并且function无法确定它是否被初始化。该函数只能检查它是否具有您用于初始化的定义值。
所以我会考虑使用一个也能进行初始化的创建函数。通过这种方式,您还可以在将其大小作为参数传递时立即为数据分配内存(或者如果您稍后想这样做,则只需 NULL)。
struct thing *newThing(size_t dataSize)
{
struct thing *t = malloc(sizeof (struct thing));
if (t)
t->data = malloc(sizeof(char) * dataSize);
// or t->data = NULL if it should be done later
return t;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
153 次 |
| 最近记录: |