就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) 我正在从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) 所分配的内存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失败时可以?
我正在尝试向我的结构添加10个元素,这个元素已经是malloc,其大小为20,这就是我定义结构的方式:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct st_temp {
char *prod;
};
int main ()
{
struct st_temp **temp_struct;
size_t j;
temp_struct = malloc (sizeof *temp_struct * 20);
for (j = 0; j < 20; j++) {
temp_struct[j] = malloc (sizeof *temp_struct[j]);
temp_struct[j]->prod = "foo";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以我想到的是重新分配(但是,不知道如何):
temp_struct = (struct st_temp **) realloc (st_temp, 10 * sizeof(struct st_temp*));
Run Code Online (Sandbox Code Playgroud)
然后添加额外的10个元素,
for (j = 0; j < 10; j++)
temp_struct[j]->prod = "some extra values";
Run Code Online (Sandbox Code Playgroud)
我怎么能实现这个目标?任何帮助表示赞赏!
我正在编写一些需要读取fasta文件的代码,因此我的部分代码(包含在下面)是一个fasta解析器.由于单个序列可以跨越fasta格式的多行,我需要将从文件读取的多个连续行连接成一个字符串.我这样做,通过在读取每一行后重新分配字符串缓冲区,成为序列的当前长度加上读入的行的长度.我做了一些其他的东西,比如剥离空白等.一切顺利第一个序列,但fasta文件可以包含多个序列.所以类似地,我有一个动态的结构数组,有两个字符串(标题和实际序列),是"char*".再次,当我遇到一个新标题(由以'>'开头的行引入)时,我增加序列数,并重新分配序列列表缓冲区.关于为第二个序列分配空间的realloc段错误
*** glibc detected *** ./stackoverflow: malloc(): memory corruption: 0x09fd9210 ***
Aborted
Run Code Online (Sandbox Code Playgroud)
对于我的生活,我不明白为什么.我通过gdb运行它,一切似乎都在工作(即一切都已初始化,值似乎是理智的)......这是代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <errno.h>
//a struture to keep a record of sequences read in from file, and their titles
typedef struct {
char *title;
char *sequence;
} sequence_rec;
//string convenience functions
//checks whether a string consists entirely of white space
int empty(const char *s) {
int i;
i = 0;
while (s[i] != 0) {
if (!isspace(s[i])) …Run Code Online (Sandbox Code Playgroud) 免责声明:这是作业.我正在尝试它,不要指望或希望任何人为我做这件事.只是几个指针(呵呵),我出错了将不胜感激.
作业要求我创建一个int*包含10个元素的数组,然后尝试在其中插入一百万个int.每个插入检查是否需要调整数组的大小,如果需要,我会增加它的大小,以便它可以容纳一个元素.
当我插入10,000个元素时,它工作正常,但如果我尝试100,000个元素,我会收到以下错误:
*** glibc detected *** ./set2: realloc(): invalid old size: 0x00000000024dc010 ***
Run Code Online (Sandbox Code Playgroud)
这是我正在运行的代码.我评论过它,因此很容易阅读.
void main()
{
//begin with a size of 10
int currentsize = 10;
int* arr = malloc(currentsize * sizeof(int));
int i;
//initalize with all elements set to INT_MAX
for(i = 0; i < currentsize; i++) {
arr[i] = INT_MAX;
}
// insert random elements
for(i = 0; i < 100000; i++) {
currentsize = add(rand() % 100,arr,currentsize);
}
free(arr);
}
/*
Method resizes …Run Code Online (Sandbox Code Playgroud) 如果您觉得需要realloc()-而且很多人都这样做-那么请考虑使用标准库向量。
我将通过同意std::vector更好的原因(因为许多原因)来开始我的问题,而我个人总是选择使用它,而不是使用C内存分配编写自己的动态数组。
但是,std::vector由于C ++没有等效的内存,内存会随着内存的增长而碎片化realloc(编辑澄清一下,我知道std::vectors的存储是连续的,不会碎片化,我的意思是分配和取消分配导致的内存空间碎片化,这realloc可以避免扩展现有分配)。那么总是推荐它公平realloc吗?小心翼翼,难道您不能编写类似于std::vectorC分配函数那样工作的东西,它可以在不移动其地址和复制现有元素的情况下增加其内存,使其在碎片和性能方面都达到或超过或提高吗?
与此相关的(奖励问题!),为什么 C ++没有与之等效的东西realloc?忽略一种专注于性能的语言,这似乎很奇怪。Bjarne的FAQ中的部分恰好具有该标题(没有强调),但是答案并未解决“为什么”的问题。只是偶然的遗漏吗?是否有与如何一些基本的不相容new/ delete工作?它真的不能真正带来实际的好处吗?
编辑:好的,所以我忽略了C的复杂性realloc- std::vector不能使用重写,realloc因为它仅适用于POD,不抛出等。在某些情况下,也许编写一个仅用于POD的容器来处理棘手问题是个好主意。无论如何,更有趣的问题变为:将std::vector受益于C ++的等价物realloc,它在(或多或少)已经在这里得到了回答:
当容量增加时std :: vector是否具有移动对象的能力?或者,分配器可以“重新分配”吗?
可悲的是,答案似乎是“是,但是标准委员会没有投票赞成”。希望如此
我的程序的目标是读取文件,并输出具有最大外观的单词以及出现次数.但我遇到了问题malloc及其语法.这是malloc指的结构:
struct Word_setup {
char word[max_length];
int count;
};
Run Code Online (Sandbox Code Playgroud)
我的主要部分帮助我发现这是我的错误:
printf("Pre-Allocation Test");
struct Word_setup *phrase;
phrase = (struct Word_setup *) malloc(SIZE);
if (phrase == NULL)
{printf("Failure allocating memory"); return 0;}
Run Code Online (Sandbox Code Playgroud)
它似乎只打印出来,Pre-Allocation Test然后冻结.正如我之前所说,我不清楚如何解决这个问题,但我已经把它隔离了.
*如果你想知道SIZE是什么:
#define SIZE (sizeof(phrase))
编辑:
对于那些对编译器版本/ OS /等感兴趣的人:Windows 7 64bit,GCC 4.9.2
如果您想了解更多信息,请告诉我.
在第56行,我正在尝试调整数组的大小:
tokenArray = (char**) realloc(tokenArray, tokSize * (sizeof(char)));
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
(11972,0x7fff7ca4f300)malloc:*对象0x100105598的错误:释放对象的校验和不正确 - 对象可能在被释放后被修改.*在malloc_error_break中设置断点以进行调试
这是一个类的编程分配,我已经被特别指示动态分配我的数组,然后根据需要进行扩展.我已经广泛搜索了同样的另一个线程,这个线程对我来说并不太先进,但没有运气......所以希望我能得到一些帮助.谢谢!这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ROW_SIZE 81
void strInput(char str[], int numElem);
int main(int argc, const char * argv[])
{
printf("Enter a string of any number of integers separated by spaces or tabs.\n");
printf("Maximum string length is 80 characters.\n");
printf("Enter an empty string to conclude input.\n");
int arrSize = 10, tokSize = 10, i = 0, j = 0;
char** inputArray = malloc(arrSize …Run Code Online (Sandbox Code Playgroud)