我必须从一个文件中读取一个未知数量的行并将它们保存到一个结构中(我希望避免使用预处理来计算元素的总数).在读取阶段之后,我必须对这些行的每个元素进行一些计算.
我想出了两种方法:
使用realloc每个我读了一排时间.这样,分配阶段很慢,但由于索引访问,计算阶段更容易.
每次我读一行时都使用链表.这样,分配阶段更快,但计算阶段更慢.
从复杂的角度来看,有什么更好的?
我正在尝试创建一个函数,该函数将数组作为参数,向其添加值(如果需要,增加其大小)并返回项的计数.到目前为止,我有:
int main(int argc, char** argv) {
int mSize = 10;
ent a[mSize];
int n;
n = addValues(a,mSize);
for(i=0;i<n;i++) {
//Print values from a
}
}
int addValues(ent *a, int mSize) {
int size = mSize;
i = 0;
while(....) { //Loop to add items to array
if(i>=size-1) {
size = size*2;
a = realloc(a, (size)*sizeof(ent));
}
//Add to array
i++;
}
return i;
}
Run Code Online (Sandbox Code Playgroud)
如果mSize足够大以容纳数组的所有潜在元素,则此方法有效,但如果需要调整大小,则会出现分段错误.
我也尝试过:
int main(int argc, char** argv) {
...
ent *a;
...
}
int addValues(ent …Run Code Online (Sandbox Code Playgroud) 就realloc的使用而言,它确实是一个建议,更具体地说,如果我可以利用它来简化我现有的代码.基本上,下面的内容,它动态分配一些内存,如果我超过256,那么数组需要增加大小,所以我malloc一个临时数组,大小2倍,memcpy等(见下文).
我只是想知道是否可以在下面的代码中使用realloc,简化它,任何建议,示例代码,甚至是如何实现它的提示非常感谢!
干杯.
void reverse(char *s) {
char p;
switch(toupper(s[0]))
{
case 'A': case 'E': case 'I': case 'O': case 'U':
p = s[strlen(s)-1];
while( p >= s )
putchar( p-- );
putchar( '\n' );
break;
default:
printf("%s", s);
break;
}
printf("\n");
}
int main(void) {
char c;
int buffer_size = 256;
char *buffer, *temp;
int i=0;
buffer = (char*)malloc(buffer_size);
while (c=getchar(), c!=' ' && c!='\n' && c !='\t')
{
buffer[i++] = c;
if ( i >= buffer_size )
{ …Run Code Online (Sandbox Code Playgroud) 我试图在Windows应用程序中使用realloc().我正在分配一大块内存,然后在我知道正确的大小后使用realloc()将其缩小.
我发现虽然realloc()似乎工作正常(任务管理器中的内存反映了你的期望),但应用程序最终会耗尽内存.从我所知道的情况来看,就好像relloc()释放内存但不释放与内存关联的虚拟地址空间.结果,malloc()最终会失败.
这是一个小型控制台应用程序,用于演示此问题:
int _tmain(int argc, _TCHAR* argv[])
{
static const DWORD dwAllocSize = (50 * 1024 * 1024);
static const DWORD dwReallocSize = 10240;
static const DWORD dwMaxIterations = 200;
BYTE* arpMemory[dwMaxIterations];
memset( arpMemory, 0, sizeof(arpMemory) );
for( DWORD i = 0; i < dwMaxIterations; i++ )
{
arpMemory[i] = (BYTE*) malloc( dwAllocSize );
if( !arpMemory[i] )
{
printf("OUT OF MEMORY after %d iterations!\n", i);
return -1;
}
BYTE* …Run Code Online (Sandbox Code Playgroud) 我正处于一个项目的中间,我正在尝试使用malloc()和realloc().我知道当我使用malloc时,它可以工作,但是当我使用realloc时,它根本不会改变分配的内存量.我总是认为realloc将重新分配你已经malloced的内存.
这是我有的:
这包括:
#include <stdlib.h>
Run Code Online (Sandbox Code Playgroud)
我有一个结构:
struct student {
int age;
int numOfClasses;
int gender; //0 male; 1 female
} student;
Run Code Online (Sandbox Code Playgroud)
当我想使用malloc制作其中7个结构时,我将使用以下代码行:
student stud* = (structure*) malloc(7*sizeof(student));
Run Code Online (Sandbox Code Playgroud)
这条线有效.该行代码采用结构的大小并乘以7乘以简而言之,这将获取足够的内存来生成7个结构的数组.
现在,如果我想将其更改为8,我会A在以前的malloced内存中执行此操作,并且B是新的malloced(或重新分配)内存:

这是我在代码中的方式:
stud = (student*)realloc(stud, 8*sizeof(student));
Run Code Online (Sandbox Code Playgroud)
据我所知,realloc在第二个参数中获取变量,mallocs获取内存量.然后,它接受指针(或之前的malloced),并尽可能多地从给定指针填充malloced内存.当然,第二个参数必须大于之前的malloced大小,否则stud最终会丢失一些内存.现在这就是我的问题所在.当我调用上面的行时,它不会改变任何东西.malloced数组仍然是7的长度.我也很确定,我有足够的内存来重新分配.
我这样做了吗?我的问题在哪里?
我正在从KandR C编程书中做一些有趣的练习.该程序用于从用户输入的一组行中查找最长行,然后打印它.
这是我写的(部分,部分内容直接取自本书): -
#include <stdio.h>
#include <stdlib.h>
int MAXLINE = 10;
int INCREMENT = 10;
void copy(char longest[], char line[]){
int i=0;
while((longest[i] = line[i]) != '\0'){
++i;
}
}
int _getline(char s[]){
int i,c;
for(i=0; ((c=getchar())!=EOF && c!='\n'); i++){
if(i == MAXLINE - 1){
s = (char*)realloc(s,MAXLINE + INCREMENT);
if(s == NULL){
printf("%s","Unable to allocate memory");
// goto ADDNULL;
exit(1);
}
MAXLINE = MAXLINE + INCREMENT;
}
s[i] = c;
}
if(c == '\n'){
s[i] = c;
++i; …Run Code Online (Sandbox Code Playgroud) 是否定义了行为实现?如果将NULL和size == 0传递给realloc():
int main(void)
{
int *ptr = NULL;
ptr = realloc(ptr, 0);
if(ptr == NULL)
{
printf("realloc fails.\n");
goto Exit;
}
printf("Happy Scenario.\n");
Exit:
printf("Inside goto.\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码应该打印"realloc failed",对吧?但事实并非如此?我已经读过某个地方,这个调用也realloc可能返回NULL.什么时候发生?
考虑这个简单的程序:
#include <string>
#include <sparsehash/dense_hash_map>
int main()
{
google::dense_hash_map<std::string, int> map;
map["foo"] = 0;
}
Run Code Online (Sandbox Code Playgroud)
使用GCC 8.2和-Wclass-memaccess(或-Wall)进行编译会产生警告:
sparsehash/internal/libc_allocator_with_realloc.h:68:40: warning:
‘void* realloc(void*, size_t)’ moving an object of non-trivially copyable type
‘struct std::pair<const std::__cxx11::basic_string<char>, int>’;
use ‘new’ and ‘delete’ instead [-Wclass-memaccess]
return static_cast<pointer>(realloc(p, n * sizeof(value_type)));
~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
问题是:
我在这里提出了一个问题:https://github.com/sparsehash/sparsehash/issues/149
所分配的内存malloc可以使用重新分配realloc。有类似的功能alloca吗?当您不希望在堆上分配内存时,并且您需要多次分配可变的堆栈内存(例如在需要动态内存但又不想动态存储的库函数中)时,重新分配堆栈内存可能很有用。在堆上分配,因为库的用户可能使用自定义堆分配策略。它看起来像这样:
int main(void) {
float * some_mem = alloca(40 * sizeof(float));
// do something with this memory...
// now we need a different amount of memory, but some_mem still occupies a lot of the stack, so just reallocate it.
// is something like this possible?
some_mem = realloca(some_mem, 50 * sizeof(float));
}
Run Code Online (Sandbox Code Playgroud)
重要的是,这一切都发生在堆栈上。问:有没有办法重新分配动态堆栈内存?
当我有一个应该重复用作参数realloc并保存其返回值的指针时,我知道realloc如果无法进行分配,则不会触及旧对象,返回NULL. 我是否还应该担心以下结构中的旧对象:
int *p = (int *)malloc(sizeof(int *));
if (p = (int *)realloc(p, 2 * sizeof(int *)))
etc...
Run Code Online (Sandbox Code Playgroud)
现在,如果realloc成功了,我需要free(p)在完成后进行。当realloc失败时,我已指定它返回NULL并且p不free(p)执行任何操作(因为它是 a free(NULL))。同时(根据标准)旧对象不会被释放。p那么我是否应该有一个(例如)的副本int *last_p = p;来跟踪旧对象,以便free(last_p)在realloc失败时可以?