C malloc和免费不起作用

时间:2016-10-26 14:14:58

标签: c pointers valgrind

我是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;
}

main.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);
    }

1 个答案:

答案 0 :(得分:2)

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

看起来问题必须在这里:

int limit = atoi(argv[1]);

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