我有一个像这样定义的结构
typedef struct {
char* Value;
unsigned int Length;
} MY_STRUCT;
我正在使用calloc创建这些结构的数组:
MY_STRUCT* arr = (MY_STRUCT*)calloc(50, sizeof(MY_STRUCT));
然后,在循环中,我正在访问每个结构并尝试使用calloc和memcpy分配值并为Value字段赋值:
int i;
for(i = 0; i < 50; i++)
{
MY_STRUCT myStruct = arr[i];
int valueLength = get_value_length(i);//for sake of example, we can assume that this function returns any value [1-99]
myStruct.Length = valueLength;
myStruct.Value = (char*) calloc(valueLength, sizeof(char));
memcpy(myStruct.Value, get_value(i), valueLength); //assume get_value(i) returns char* pointing to start of desired value
}
此代码块在calloc行上崩溃,Visual Studio指示堆损坏 . 第一次通过循环时它不会失败 . 相反,当我尝试分配长度为20的char数组时,它在第二遍时失败(第一遍是长度为5) . 我也尝试过使用malloc,我尝试过使用以下建议:
Heap Corruption with malloc, struct and char *
Do I cast the result of malloc?
似乎没有什么能够缓解这个问题 . 我原来是一个托管代码程序员,所以我对内存分配和管理的了解并不总是最好的 . 我确定我正在做一些愚蠢的事,但我不确定是什么 . 任何帮助将不胜感激 . 谢谢!