C的malloc和free不起作用



我是C语言的新手,我在使用malloc和free时遇到了一些麻烦。我想不出问题在哪里。我有一个程序,有prime.c和main.c

我为我的数组使用malloc分配,当我在main.c中调用free时,valgrind显示这个错误

==13518==     in use at exit: 0 bytes in 0 blocks
==13518==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==13518== 
==13518== All heap blocks were freed -- no leaks are possible
==13518== 
==13518== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
==13518== 
==13518== 1 errors in context 1 of 1:
==13518== Invalid read of size 1
==13518==    at 0x40D2DFB: ____strtol_l_internal (in /usr/lib/libc-2.23.so)
==13518==    by 0x40D2C68: strtol (in /usr/lib/libc-2.23.so)
==13518==    by 0x40CFAFF: atoi (in /usr/lib/libc-2.23.so)
==13518==    by 0x80487B0: main (in /media/test/prime)
==13518==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==13518== 
==13518== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

这是我的两个类

prime.c

    #include <stdio.h>
#include <stdlib.h>
#include "prime.h"
#include <stdint.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
uint64_t* findPrime(uint64_t max ,size_t* primeCount)
{
    int cnt=0;
    uint64_t *array;
    array = (uint64_t *) malloc(max * sizeof(uint64_t));

    if(array ==NULL)
    {
    return (uint64_t*) 1;
    }

for(int i =2; i < max;i++)
    {
    array[i] = i;
    }
for(int i = 2;i <= sqrt(max);i++)
    {
    if(array[i] != 0)
    {
for(int j = (i*i); j< max; j =j+i)
        {
    array[j] = 0;
        }
    }
    }
for(int i =2; i <max; i++)
    {
        if(array[i])
        {
        cnt++;
        }
    }
    *primeCount = cnt;
return array;
}

c

#include <stdio.h>
#include <stdlib.h>
#include "prime.h"
#include <string.h>
int main(int argc, char* argv[]){
    int len = argc-1;
    int limit = atoi(argv[1]);
    int ret =1;
    size_t pc =0; 

    if(len == 1)
    {
    limit = atoi(argv[1]);
    }
    else if(len == 2)
    {
    limit = atoi(argv[2]);
    ret = strcmp(argv[1],"-p");
    if(ret != 0)
    {
    printf("Invalid input!n");
    return 1;
    }
    }
    else
    {
    printf("Wrong number of arguments!!!n");
    return 1;    
    }
    uint64_t* primes  = findPrime(limit, &pc);
       printf("Total number of primes %zu n", pc);
    if(ret == 0)
    { 
        for(int i =2; i < limit;i++)
        {
        if(primes[i] != 0)
        {
            printf("primess: %lld n", primes[i]);
        }    
        }
    }
    free(primes);
    }

valgrind输出中的堆栈跟踪将错误归因于main()atoi()的三个调用中的一个。具体的问题似乎是传递给该函数的空指针。每个atoi()调用的参数都是argv数组的一个元素,因此您的(直接)问题是程序参数处理,而不是动态内存分配。

看起来问题一定在这里:

int limit = atoi(argv[1]);

无条件地执行atoi()调用,但是当argc小于2时,它会显示未定义的行为。

最新更新