【发布时间】:2014-02-24 15:11:45
【问题描述】:
据我所知,malloc 在内存中分配了特定数量的字节。但是我正在尝试使用它并且我分配了 4 个字节但是当我尝试在数组中存储超过 4 个(最多 200 个整数)元素时它没有给我任何错误!所以在我的代码中我不需要使用 realloc!!顺便说一句,我正在使用 Linux。最后,我很高兴听到您的任何建议......提前致谢。
tmp.h:
#ifndef TMP_H
#define TMP_H
#define MAXLENGTH 4
#define GROWFACTOR 1.5
typedef struct stVector
{
int *vec;
int length;
int maxLength;
}Vector;
Vector newEmptyVector();
void addElement(Vector *vec, int elt);
#endif
tmp.c:
#include "stdio.h"
#include "stdlib.h"
#include "tmp.h"
Vector newEmptyVector()
{
Vector vec;
vec.vec = (int*) malloc(0);
printf("Allocating %d bytes\n", sizeof(int)*MAXLENGTH );
vec.length = 0;
vec.maxLength = MAXLENGTH;
return vec;
}
void addElement(Vector *vec, int elt)
{
/*if(vec->length == vec->maxLength)
{
vec->vec = (int*)realloc(vec->vec,sizeof(int)* vec->maxLength * GROWFACTOR);
vec->maxLength = vec->maxLength * GROWFACTOR;
}*/
vec->vec[vec->length++] = elt;
}
main.c:
#include"tmp.h"
int main(int argc, char const *argv[])
{
Vector vector = newEmptyVector();
printf("The length is %i and maxlength is ` `%i\n",vector.length,vector.maxLength);
addElement(&vector,5);
addElement(&vector,3);
addElement(&vector,1);
addElement(&vector,7);
printf("The length is %i and maxlength is ` `%i\n",vector.length,vector.maxLength);
addElement(&vector,51);
printf("The length is %i and maxlength is %i\n",vector.length,vector.maxLength);
for (int i = 0; i < 200; ++i)
{
addElement(&vector,i);
printf("The length is %i and maxlength is %i\n" ,vector.length, vector.maxLength);
}
return 0;
}
【问题讨论】:
-
它在哪里指定当你破坏堆时它会立即崩溃?
-
这就是我们所说的未定义行为。任何事情都有可能发生。
-
当您执行
malloc(0)时,您分配 零 个字节。你会得到eitherNULL或一个有效的指针(你可以传递给free)作为回报。如果你得到一个非空指针作为回报,它指向你分配的那个零大小的内存区域,你不能使用它(因为它的大小为零)。 -
另外,在 C don't cast the result of
malloc. -
您还应该检查
malloc和realloc的返回值以确保它们成功。这说明了您调用realloc的方式存在问题,因为如果它失败了,它将清除您唯一指向内存的指针。