#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n int *ptr;\n int n;\n\n printf("Enter the no of elements you want in an array1:");\n scanf("%d",&n);\n printf("The no of elements in array 1 would be %d",n);\n\n ptr=(int*)malloc(n*sizeof(int));\n if(ptr==NULL){\n printf("Memory not alloted ");\n }\n else{\n printf("Memory successfully alloted using malloc");\n }\n\n printf("The elements of array 1 are:");\n for(int i=0;i<n;i++){\n ptr[i]=2*i;\n printf("%d",ptr[i]);\n }\n free(ptr);\n printf("Memory has been successfully freed\\n");\n\n int *ptr1,n1;\n printf("Enter the no of elements you want in an array2:\\n");\n scanf("%d",&n1);\n printf("The no of elements in array 2 …Run Code Online (Sandbox Code Playgroud) 我有一个函数,它读取文件并为文件内容分配内存,并将文件内容分配给指针,然后返回指针。然后,我使用循环来遍历字符串并使用指针算术打印每个字符。
我很确定我可以/应该使用 realloc 在每次迭代中重新分配更少的内存,而不是使用计数器跟踪迭代,但我不确定如何实现它。
因此,在代码末尾,当我调用时,free()我从指针变量中减去计数器,以释放contents指针最初指向的地址。
下面是我用来读取文件的代码以及循环所在的主函数:
char *read_file(const char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
perror("Failed to open file");
exit(EXIT_FAILURE);
}
// Obtain information about the file
struct stat st;
if (fstat(fileno(fp), &st) != 0) {
perror("Failed to get file information");
exit(EXIT_FAILURE);
}
size_t file_size = st.st_size;
// Allocate a buffer to hold the contents of the file
char *buffer = (char *) malloc(file_size + 1);
if (buffer == NULL) …Run Code Online (Sandbox Code Playgroud) 我编写了一个简单的程序来实现基于动态数组的堆栈。realloc已用于调整我用来存储堆栈元素的容器的大小。
#include <stdio.h>
#include <stdlib.h>
void stack_push(int **stack, int *stackSize, int element);
int stack_pop(int **stack, int *stackSize);
int main()
{
char ch;
int *stack = NULL, stackSize = 0;
do
{
printf("\n1. Push\n");
printf("2. Pop\n");
printf("Exit (0)\n");
printf("Enter choice : ");
scanf("%c", &ch);
switch(ch)
{
case '1':
stack_push(&stack, &stackSize, 1);
break;
case '2':
printf("%d\n", stack_pop(&stack, &stackSize));
break;
case '0':
break;
}
} while (ch != '0');
return 0;
}
void stack_push(int **stack, int *stackSize, int element)
{
if …Run Code Online (Sandbox Code Playgroud) c stack realloc segmentation-fault dynamic-memory-allocation
显然SDL_Mixer中的这个功能一直在死,我不知道为什么.有没有人有任何想法?根据visual studio的说法,崩溃是由Windows在realloc()行的某处触发断点引起的.
有问题的代码来自SDL_Mixer的SVN版本,如果这有所不同.
static void add_music_decoder(const char *decoder)
{
void *ptr = realloc(music_decoders, num_decoders * sizeof (const char **));
if (ptr == NULL) {
return; /* oh well, go on without it. */
}
music_decoders = (const char **) ptr;
music_decoders[num_decoders++] = decoder;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用Visual Studio 2008,music_decoders和num_decoders都是正确的(music_decoders包含一个指针,字符串"WAVE"和music_decoders.ptr是0x00000000,我能说的最好,崩溃似乎在realloc中()函数.有没有人知道如何处理这个崩溃问题?我不介意做一些重构以使这项工作,如果它归结为那.
忍受我.我在8年内没有用c编码,我完全不知道为什么我的字符串操作不起作用.我正在写一个永远循环的程序.在循环中,我初始化两个char指针,每个指针都传递给一个向char指针(数组)添加文本的函数.函数完成后,我打印char指针并释放两个char指针.但是,程序在7次迭代后死亡,并显示以下错误消息
*glibc检测到* ./test:双重免费或损坏(fasttop):0x0804a168***
#include sys/types.h
#include sys/stat.h
#include fcntl.h
#include string.h
#include stdio.h
#include stdlib.h
#include errno.h
#include time.h
char *SEPERATOR = "|";
void getEvent (char* results);
void getTimeStamp(char* timeStamp, int timeStampSize);
void stringAppend(char* str1, char* str2);
int main (int argc, char *argv[])
{
int i = 0;
while(1)
{
i++;
printf("%i", i);
char* events= realloc(NULL, 1);
events[0] = '\0';
getEvent(events);
char* timestamp= realloc(NULL, 20);
timestamp[0] = '\0';
getTimeStamp(timestamp, 20);
printf("%s", events);
printf("timestamp: %s\n", timestamp);
free(events);
free(timestamp);
}
}
void …Run Code Online (Sandbox Code Playgroud) 所以我在我的程序中使用malloc然后在程序内部的方法中重新分配.在我多次调用这个方法之后,我会得到一个"Segmentation fault(core dumped)".
经过进一步检查,我意识到由于某种原因,当我的指针从0x25d7d60或0x223fae0(或任何由7位数字(0xHHHHHHH)表示的地址)变为0x7f47d370a010(超过7位数)时,会从realloc调用中抛出一个段错误,realloc甚至不会返回NULL.我通过简单地使用malloc然后使用memcpy来修复此问题.但是我很困惑,为什么会发生这种情况,并希望看看stackoverflow的任何用户是否能够解释为什么会发生这种情况.
谢谢
这是相关代码:
unsigned int* myArray;
unsigned int num_ints;
int main()
{
num_ints = 100;
if((myArray =(unsigned int*) malloc(sizeof(unsigned int)*(num_ints)*3))==NULL)
{
std::cout << "Malloc failed!" << std::endl;
return false;
}
.
.
.
//This called when n key is pressed (code left out)
methodName();
return true;
}
void methodName()
{
if((myArray =(unsigned int*) realloc(myArray,sizeof(unsigned int)*(num_ints*4)*3))==NULL)
{
std::cout << "Realloc failed!" << std::endl;
exit(0);
}
}
Run Code Online (Sandbox Code Playgroud) 我知道realloc必要时会释放记忆,而且我知道C的第三条规则 - "每一个malloc必须有一个平等和相反的free"......但这两个如何一起工作?
最好在代码中描述这种情况:
int main()
{
myStruct **myStructArray;
int i, num_elements;
num_elements = getnumber(); // gets value for num_elements
myStructArray = (myStruct **) malloc(num_elements * sizeof(myStruct*));
for (i=0; i<num_elements; i++)
myStructArray[i] = (myStruct *) malloc(sizeof(myStruct));
// so far so good...
num_elements = getnumber(); // gets new, LOWER value
myStructArray = realloc(myStructArrary, num_elements * sizeof(myStruct*));
// rest_of_code, and necessary free loop for myStructArray etc...
}
Run Code Online (Sandbox Code Playgroud)
显然,上面只不过是一个片段,但是一个片段描绘了千言万语.
这会造成内存泄漏吗?我知道调用realloc将释放指针的内存,但我可以看到赞成和反对可能存在一堆内存被遗忘的可能性.
在调用释放(现在为NULL)指针之前,可以通过合并int number_elements_new到代码中并循环free …
我有一个非常简单的C代码,它使用malloc和realloc,但是如果我更改了属于第一个数组的值,它就会引发seg错误.
#include <stdlib.h>
void increase(int** array)
{
int * new_array;
new_array = realloc(*array, 10 * sizeof(int));
if (new_array != NULL) {
*array = new_array;
}
else {
// Error in reallocation
}
int i = 3;
*array[i] = 2; // Seg fault if i = 0, 1, 2, 3
}
main()
{
int *array = malloc(4 * sizeof(int));
increase(&array);
free(array);
}
Run Code Online (Sandbox Code Playgroud)
我对错误指针的理解是什么?任何人都可以解释发生了什么以及如何正确使用realloc?
非常感谢!
我试图动态分配一个结构数组但是每当我运行程序时我都会得到:a.out(6487,0x7fff7ecb8300)malloc:*对象0x7fff6f670000的错误:没有分配重新分配的指针*在malloc_error_break中设置一个断点调试
struct node {
char course[25];
char category[20];
char prereq[50];
char notes[50];
};
int main(int argc, char* argv[])
{
FILE *fp;
char *filename = argv[1];
char *token;
char buffer[100];
char *del = ",\n";
int num = 5, i = 0, j =0, count = 0;
struct node *d = malloc(num * sizeof(struct node));
char** complete = malloc(num * sizeof(char*));
printf("%s\n", filename);
if( (fp = fopen(filename, "r")) == NULL )
{
printf("unable to open %s\n", filename);
exit(1);
}
while(fgets(buffer, …Run Code Online (Sandbox Code Playgroud) 当输入为'1 2 3 4 5 6 7 8 9 10 11'时预期输出应与输入相同.然而输出是'1 2 3 4 5 6 7 8 9 10 -1850774484'.仅在输入的整数超过10时才会发生.我的realloc系列在哪里出错了
#include <stdio.h>
#include <stdlib.h>
#define INITIAL_SIZE 10
int
main(int argc, char **argv){
int i = 0, num, size = 0, n = INITIAL_SIZE;
int *A;
A = malloc(n * sizeof(int));
if(A == NULL){
printf("OUT OF MEMORY\n");
exit(EXIT_FAILURE);
}
while(scanf("%d",&num) == 1 && getchar()!='\n'){
A[i] = num;
i++;
size++;
if (size >= n){
n = n * 2;
A = …Run Code Online (Sandbox Code Playgroud) realloc ×10
c ×8
malloc ×6
free ×3
c++ ×2
allocation ×1
arrays ×1
breakpoints ×1
calloc ×1
corruption ×1
memory ×1
stack ×1
windows ×1