gpt4 book ai didi

c - 在堆中分配函数的返回值

转载 作者:行者123 更新时间:2023-11-30 18:46:32 24 4
gpt4 key购买 nike

我在程序的部分分配函数的返回值时遇到问题。当我在 main 中尝试它时,它给出了错误“段错误”。我相信这是因为我的数组的大小,这是我之前提到的返回值,因为当我将 max_size 变小时,代码可以正常工作(我认为最多为 45000)。当我在main中调用该函数时,它使用堆栈的内存,该内存比堆的内存小得多。因此,我尝试调用堆中的函数并在那里进行赋值,但编译器给出了错误

deneme.c:6:15: error: initializer element is not constant
int *primes = listPrimes(1000000, &size);

之后我做了一些研究,发现堆栈是 8 MB 内存,大约是 8000000 字节。然后我使用素数定理估计了我的数组大小(最多 1000000,大约有 200000 个素数)和 sizeof(int) = 4 bit值,因此它给出 100000 字节,远小于 8 MB。因此我有两个问题:

1. Why the compiler gives segmentation fault error although my array size is not too large?

2. How can I make the assigment in heap instead of main in order to avoid this problem?

这是我的代码:

#include "mathlib.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>

int *listPrimes(int max_size, int *size) {
*size = 1;
int *result = malloc(*size * sizeof(int));
int i;
int index = 1;
// Finding the list of primes using a sieve algorithm:
int *nums = malloc(max_size*sizeof(int));
for (i = 0; i < max_size; i++) {
nums[i] = i;
}
result[0] = 2;
int j = 2;
while (j < max_size) {
int k = j;
while (j*k <= max_size) {
nums[j*k] = 0;
k++;
}
if (j == 2) {
j++;
*size = *size + 1;
result = realloc(result, *size * sizeof(int));
result[index++] = nums[j];
}
else {
j += 2;
if (nums[j] != 0) {
*size = *size + 1;
result = realloc(result, *size * sizeof(int));
result[index++] = nums[j];
}
}
}
return result;
}

主要功能:

#include <stdio.h>
#include <stdlib.h>
#include "mathlib.h"

int size = 0;
int *primes = listPrimes(1000000, &size);

int main() {
printf("size = %d\n", size);
for (int i = 0; i < size; i++) {
printf("%d th prime is %d\n", i+1, primes[i]);
}
free(primes);
return 0;
}

最佳答案

在listPrimes中使用unsigned int表示j、kmax_size并且工作正常。下面是经过测试的代码:

// #include "mathlib.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>

int size = 0;

int *
listPrimes (unsigned int max_size, int *size)
{
*size = 1;
int *result = malloc (*size * sizeof (int));
int i;
int index = 1;
// Finding the list of primes using a sieve algorithm:
int *nums = malloc (max_size * sizeof (int));
for (i = 0; i < max_size; i++)
{
nums[i] = i;
}
result[0] = 2;
unsigned int j = 2;
while (j < max_size)
{
unsigned int k = j;
while (j * k <max_size)
{
nums[j * k] = 0;
k++;
}
if (j == 2)
{
j++;
*size = *size + 1;
result = realloc (result, *size * sizeof (int));
result[index++] = nums[j];
}
else
{
j += 2;
if (nums[j] != 0)
{
*size = *size + 1;
result = realloc (result, *size * sizeof (int));
result[index++] = nums[j];
}
}
}
free(nums);
return result;
}

int
main ()
{
int *primes = listPrimes (1000000, &size);
printf ("size = %d\n", size);
for (int i = 0; i < size; i++)
{
printf ("%d th prime is %d\n", i + 1, primes[i]);
}
free (primes);
return 0;
}

关于c - 在堆中分配函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50816486/

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