gpt4 book ai didi

c - 函数内的动态内存分配不起作用,但没有发生错误

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

<分区>

我想为一个字符数组分配内存。因此,我编写了一个函数,返回值告诉我,如果我检查它,一切正常。但是当我尝试在数组中写入时,会发生段错误。如果我在没有函数的情况下分配内存(源代码的注释区域),一切似乎都工作正常。

#include <stdio.h>
#include <stdlib.h>
#define ENWIK8 100000000
#define FILEPATH_INPUT "enwik8"
#define FILEPATH_OUTPUT "ergebnis/enwik8"

int array_alloc(char* array, int size);
int array_fill(FILE* file, char* path, char* array);

int main()
{

FILE* enwik8_file;
char *text_original;
array_alloc(text_original, ENWIK8);

//THIS CODE WOULD WORK BUT NOT THE FUNCTION WITH SAME CODE
// text_original = calloc(ENWIK8,sizeof(char));
// if(text_original == NULL)
// {
// perror("Allocating array not possible!");
// return -1;
//
// }

//Leads to: segmentation fault, if the function is used
//instead of the code above
text_original[1000000] = 'a';
return 0;
}



int array_alloc(char* array, int size)
{

array = (char*)calloc(size,sizeof(char));
if(array == NULL)
{
perror("Allocating array not possible!");
return -1;

}
else
{
return 0;
}
}

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