gpt4 book ai didi

c - malloc->分配了多少内存?

转载 作者:太空宇宙 更新时间:2023-11-04 05:18:47 25 4
gpt4 key购买 nike

<分区>

据我所知,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;
}

主.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;
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com