2016-05-25 5 views
-3

Kann dieses Problem nicht lösen - mein Compiler sagt mir immer, dass ich einige Probleme mit der freien (Zeiger) Funktion habe. Ich bin mir also nicht sicher über die Funktionsweise meiner Zeiger, aber das Debugging hat gezeigt, dass eigentlich alles gut funktioniert. Nur die freie Funktion konnte den Speicher nicht freigeben.wie man malloc außerhalb der Funktion freigibt

#include <stdio.h>    //Bibliothek für input/output. 
    #include <stdlib.h>    //For malloc 
    #include <math.h>    //Bibliothek für matchematische Operationen. 
    #include <iostream>    //Bibliothek für in/output in C++. 
    #include <stdbool.h>   //Bibliothek für boolean 

    //Prototypes 
int* readNumbers(int size); 
int sumUpNumbers(int* sumpointer, int size); 

//Main function 
int main() 
{ 
    int arraySize; //Size of the malloc-array 
    int* pointer; //pointer for storing of the malloc-address 
    int total;  //variable for the sumUpNumbers function 
    pointer = NULL; //point on zero 

    //inform the user before getting a number from him 
    std::cout << "Please give the size of array:" << std::endl; 
    fflush(stdout); //free the output window 
    //get a number for the size of array 
    scanf("%d", &arraySize); 

    //call the readNumbers function and store the first address of 
    //the malloc-array in pointer 
    pointer = readNumbers(arraySize); 

    //call the sumUpNumbers function and store the number in total 
    total = sumUpNumbers(pointer, arraySize); 

    fflush(stdout); //free the output window 
    //show the number from total 
    printf("\n total of the array:%d", total); 

    //call the free function for making the memory of 
    //the malloc-array free again 
    free(pointer); 

    fflush(stdin); //free the keyboard buffer 
    getchar();  //wait for a feedback from user 
    return 0;  //return 0 to the machine in case if everything works well 
} 


//This function has a pointer extension because we want to work with the 
//array outside of this function. We give the function a size of the array 
//we want to build. The function builds an array and fills it with numbers 
//and than gives us back the first address of the array. 
int* readNumbers(int size) 
{ 

    int* array;   //pointer for creating of malloc-array 
    int i;    //counter 

    //pointer for storing of the first address of the array 
    int* helpPointer; 
    array = NULL;  //set the pointers 
    helpPointer = NULL; //    on zero 

    //create the array 
    array = (int *) malloc(size * sizeof(int)); 

    //check the value of the array to be sure that we have created 
    //the array without errors 
    if(array != NULL) 
    { 
     //store the first address of the malloc-pointer 
     helpPointer = array; 
     //give some value to all the parts of array 
     for(i=0; i<=size; i++) 
     { 
      //inform the user 
      printf("\n give the %d. nummber of the array:\n", i+1); 
      fflush(stdout); //free the output window 
      //read the value 
      scanf("%d", array+i); 
     } 

     return helpPointer; //return the first address 
    } 
    //if something went wrong by creating of the array, do: 
    else 
    { 
     //tell the user, what we computer does't have enough memory 
     std::cout << "There is no place for saving the data in mamory"; 
     return 0; //return with failure 
    } 

} 

//The input of this function is a pointer with the address of the malloc-array 
//from the readNumbers and the size of this array. The function adds all the numbers 
//from the array and gives us the result of the additation back. 
int sumUpNumbers(int* sumpointer, int size) 
{ 
    int sum; //variable for storing of total value 
    int i;  //counter 
    sum = 0; //set the sum on zero before work with it 

    //count all the values from the array 
    for(i=0; i<=size; i++) 
    { 
     //count one number after another 
     sum = sum + *(sumpointer+i); 
    } 
    return sum; //return the total value 
} 
+3

'fflush (stdin);' Ruft undefiniertes Verhalten auf und kann zum Absturz des Programms führen. Sind Sie sicher, dass das nicht das eigentliche Problem ist? Entferne einfach diese Zeile. – Lundin

+3

'für (i = 0; i <= Größe; i ++)' überschreitet den zugewiesenen Speicher. Hinweis: Sie haben keinen "Compiler-Fehler". Hast du nicht bemerkt, dass es um einen weiteren Eintrag geht, als du es gesagt hast? –

+2

Ich bin ziemlich sicher, dass Ihr Compiler Ihnen nicht sagt, dass Sie ** einige Probleme haben **. Sicher ist es spezifischer als das. Warum auch malloc in C++ benutzen? – user2079303

Antwort

2

Die Grenzen Ihrer for Schleifen sind falsch. Sie schreiben in eine Position über dem Ende Ihres Arrays, die den Speicher beschädigen könnte, damit das Programm später fehlschlägt. Ändern Sie die for Schleifen:

for(i=0; i<size; i++) 
2

In der readNumbers Funktion Sie haben:

for(i=0; i<=size; i++) 

aber das Array ist nur size Elemente lang, so dass nur ändern <=-<:

for(i=0; i < size; i++) 

Sie haben das gleiche Problem in der sumUpNumbers Funktion. Dies führt jedoch höchstwahrscheinlich nur zu einer falschen Summe, obwohl es technisch undefiniert ist.

1

Ihr Code hat einige Probleme:

  1. fflush(stdin) ein Generator von undefinierten Verhalten ist.
  2. zwei falsche Zähler: wenn Größe size ist, Sie for(i = 0; i < size; i++)
  3. Ihre int* readNumbers(int size) Renditen zu rechnen müssen int statt int* wenn arrayNULL ist.
  4. seltsame Mischung von C und C++ ohne ersichtlichen Grund zu cin und cout mit von

Neben drei offensichtliche Fehler (1) und (2) und (3) geschrieben zu haben, Sie schieben sie auch verwenden C++ Compiler (4) zum Kompilieren von etwas, von dem 99% reiner C-Code ist. Warum?

Falls Sie ersetzen cin und cout mit entsprechenden scanf() und printf() Anrufe, Sie von C++ loszuwerden. Sie können also einen C-Compiler verwenden. In diesem Fall stellen Sie sicher, auch malloc Aufruf zu ändern, um den C Standard entsprechen:

array = malloc(size * sizeof(int)); //no result casting! 

Dann sind Sie 100% von C-Code erhalten, die leichter zu lesen ist, zu studieren und zu debuggen.

+0

OP kompiliert [Tag: C++] Code, so dass 'malloc' Rückgabewert Cast obligatorisch ist. – LPs

+0

Ich hoffe meine Antwort ist klar genug. Ich habe OP auf die Möglichkeit hingewiesen, den Code zu vereinfachen und zu 100% ** plain C ** zu machen, anstatt einen C++ - Compiler für Code verwenden zu müssen, der ** <1% C++ **, @LPs ist. Aus irgendeinem Grund ist es mit C und C++ markiert, was mehrdeutig ist. (-: – user3078414

+0

@ user3078414 Wenn Sie Problem 4 zu Ihrer Liste hinzufügen, wird es voll sein, glaube ich. Es gibt 0 zurück in readNumbers(). Wenn geändert NULL zurück in C, wird es die Portabilität erhöhen. –