简体   繁体   中英

Memory leaks in C?

I'm currently learning to program in C. In one of the tasks in my assignment, I have to make a histogram (drawn by basic console output, like this: http://img703.imageshack.us/img703/448/histogram.jpg ) to measure the number of characters in a text file (standard for this assignment is 1.3 MB). I did make a function like this:

int *yAxisAverageMethod(int average, int max, int min)
{
    int *yAxis;
    int i=0;
    for (i=0;i<20;i++)
    {
        *(yAxis+i)=0;
    }
/*
    int length=sizeof(data)/sizeof(int);
*/
    int lower_half_interval=average/10;
    int upper_half_interval=(max-average)/10;
    int current_y_value=min;
        for (i=0;i<11;i++)
        {
            if (i==10){
                *(yAxis+10)=average;
                break;
            }
            *(yAxis+i)=current_y_value;
            current_y_value+=lower_half_interval;            
        }
    current_y_value+=average+upper_half_interval;
    printf("Current y value:%d\n",current_y_value);
    printf("Current max value:%d\n",max);
        for (i=11;i<20;i++)
        {
                *(yAxis+i)=current_y_value;
                current_y_value+=upper_half_interval;
        }

    return yAxis;
}

In this function, I intend to return an array of 20 integers, in order to make ay axis. I find the average of all characters, then used 20 lines of the console to display it. The lower 10 lines are used to display the lower than average values of the total amount of characters, and 10 lines are used to display the upper part. Each step in the y axis of the lower half is calculated by (average - min)/10, and each step in the y axis of the upper part is calculated by (max - average)/10. This is my method to draw the histogram, because I want to display the variants between values.

In the main method, I have this function call:

int *yAxis;
yAxis=yAxisAverageMethod(average,max,min);

I got a segmentation fault when I ran the function. In netbean GCC++ compiler, it works fine. Howerver, when I ran it on the university machines (which I have to compile it on command line and edit in Vi), I got the error. I guess it is because Netbean has its own memory manager? I don't understand.

Edited: I will ask about merge sort in anothe question.

*yAxis is a wild pointer. You never allocate memory for the int array you want to use.

int *yAxis = malloc(sizeof(int) * 20);

You are returning a pointer to nothing.

Where inside the function do you tell the computer to reserve some memory for *yAxis?

yAxis is a point, and you did not initialize it. it will point to unknown space what depends on the compiler. you should apply some memory for it firstly.

yAxis = malloc(sizeof(int)*20);

不要忘记在调用者中释放它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM