realloc() problems with the old size












0














I want to read a lot of information from a file, so I need a dynamic memory.
This is why I use malloc for my struct in the main.
I wanted to realloc with every new line I get from the file, but he says "realloc(): invalid old size", and does not even realloc once.



typedef struct{
int anzahl;
int ANR;
char MHD[10];
char Bezeichnung[20];
char VPE[5];
float Preis;
float gesamtpreis;
}Ware;

int DateiLesen(Ware *Rechnung)
{
FILE *datei_lesen = NULL;
char trennung = " :,;n=";
char zeilen_lesen[256] = {0};
char *formatierer = NULL;
int count = 0;

datei_lesen = fopen("artikel.txt","r");
while(fgets(zeilen_lesen,256,datei_lesen))
{
count++;
}
fclose(datei_lesen);
if(count == 0)
{
return -1;
}
datei_lesen = fopen("artikel.txt","r");
while(fgets(zeilen_lesen,256,datei_lesen))
{
fputs(zeilen_lesen,datei_lesen);
formatierer = strtok(zeilen_lesen,trennung);
if(atoi(formatierer) >= 100000)
{
Rechnung->ANR = atoi(formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->MHD,formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->Bezeichnung,formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->VPE,formatierer);
formatierer = strtok(NULL,trennung);
Rechnung->Preis = atoi(formatierer);
Rechnung = realloc(Rechnung,1*sizeof(Ware));
//Rechnung = (Ware*) realloc(Rechnung,1);
Rechnung++;
}
}
fclose(datei_lesen);
return 0;
}


int main(void) {
Ware *Rechnung = (Ware*) malloc(sizeof(Ware));
int test = 0;

initialisiere(&Rechnung);
test = DateiLesen(&Rechnung);
return EXIT_SUCCESS;
}









share|improve this question




















  • 4




    your signature for the DateiLesen function doesn't match the parameters that you pass in. Do you see any compiler warnings? DateiLesen says it wants a pointer to i.e. a *Ware type, but you have passed in a **Ware type.
    – bruceg
    Nov 19 at 21:36








  • 1




    StackOverflow does not really require perfect English, or I myself would be pretty lost. But please try a little harder to avoid the impression that you cannot be bothered with punctuation, capitalisation only where appropriate and basic grammar. You will not actually insist that you really think "wanna" is correct, will you? Giving instead the impression that you at least tried will give you better reactions. Also even in code, using English words for identifiers will make your question/code easier to understand for the majority of potential answerers.
    – Yunnosch
    Nov 19 at 21:43
















0














I want to read a lot of information from a file, so I need a dynamic memory.
This is why I use malloc for my struct in the main.
I wanted to realloc with every new line I get from the file, but he says "realloc(): invalid old size", and does not even realloc once.



typedef struct{
int anzahl;
int ANR;
char MHD[10];
char Bezeichnung[20];
char VPE[5];
float Preis;
float gesamtpreis;
}Ware;

int DateiLesen(Ware *Rechnung)
{
FILE *datei_lesen = NULL;
char trennung = " :,;n=";
char zeilen_lesen[256] = {0};
char *formatierer = NULL;
int count = 0;

datei_lesen = fopen("artikel.txt","r");
while(fgets(zeilen_lesen,256,datei_lesen))
{
count++;
}
fclose(datei_lesen);
if(count == 0)
{
return -1;
}
datei_lesen = fopen("artikel.txt","r");
while(fgets(zeilen_lesen,256,datei_lesen))
{
fputs(zeilen_lesen,datei_lesen);
formatierer = strtok(zeilen_lesen,trennung);
if(atoi(formatierer) >= 100000)
{
Rechnung->ANR = atoi(formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->MHD,formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->Bezeichnung,formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->VPE,formatierer);
formatierer = strtok(NULL,trennung);
Rechnung->Preis = atoi(formatierer);
Rechnung = realloc(Rechnung,1*sizeof(Ware));
//Rechnung = (Ware*) realloc(Rechnung,1);
Rechnung++;
}
}
fclose(datei_lesen);
return 0;
}


int main(void) {
Ware *Rechnung = (Ware*) malloc(sizeof(Ware));
int test = 0;

initialisiere(&Rechnung);
test = DateiLesen(&Rechnung);
return EXIT_SUCCESS;
}









share|improve this question




















  • 4




    your signature for the DateiLesen function doesn't match the parameters that you pass in. Do you see any compiler warnings? DateiLesen says it wants a pointer to i.e. a *Ware type, but you have passed in a **Ware type.
    – bruceg
    Nov 19 at 21:36








  • 1




    StackOverflow does not really require perfect English, or I myself would be pretty lost. But please try a little harder to avoid the impression that you cannot be bothered with punctuation, capitalisation only where appropriate and basic grammar. You will not actually insist that you really think "wanna" is correct, will you? Giving instead the impression that you at least tried will give you better reactions. Also even in code, using English words for identifiers will make your question/code easier to understand for the majority of potential answerers.
    – Yunnosch
    Nov 19 at 21:43














0












0








0







I want to read a lot of information from a file, so I need a dynamic memory.
This is why I use malloc for my struct in the main.
I wanted to realloc with every new line I get from the file, but he says "realloc(): invalid old size", and does not even realloc once.



typedef struct{
int anzahl;
int ANR;
char MHD[10];
char Bezeichnung[20];
char VPE[5];
float Preis;
float gesamtpreis;
}Ware;

int DateiLesen(Ware *Rechnung)
{
FILE *datei_lesen = NULL;
char trennung = " :,;n=";
char zeilen_lesen[256] = {0};
char *formatierer = NULL;
int count = 0;

datei_lesen = fopen("artikel.txt","r");
while(fgets(zeilen_lesen,256,datei_lesen))
{
count++;
}
fclose(datei_lesen);
if(count == 0)
{
return -1;
}
datei_lesen = fopen("artikel.txt","r");
while(fgets(zeilen_lesen,256,datei_lesen))
{
fputs(zeilen_lesen,datei_lesen);
formatierer = strtok(zeilen_lesen,trennung);
if(atoi(formatierer) >= 100000)
{
Rechnung->ANR = atoi(formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->MHD,formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->Bezeichnung,formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->VPE,formatierer);
formatierer = strtok(NULL,trennung);
Rechnung->Preis = atoi(formatierer);
Rechnung = realloc(Rechnung,1*sizeof(Ware));
//Rechnung = (Ware*) realloc(Rechnung,1);
Rechnung++;
}
}
fclose(datei_lesen);
return 0;
}


int main(void) {
Ware *Rechnung = (Ware*) malloc(sizeof(Ware));
int test = 0;

initialisiere(&Rechnung);
test = DateiLesen(&Rechnung);
return EXIT_SUCCESS;
}









share|improve this question















I want to read a lot of information from a file, so I need a dynamic memory.
This is why I use malloc for my struct in the main.
I wanted to realloc with every new line I get from the file, but he says "realloc(): invalid old size", and does not even realloc once.



typedef struct{
int anzahl;
int ANR;
char MHD[10];
char Bezeichnung[20];
char VPE[5];
float Preis;
float gesamtpreis;
}Ware;

int DateiLesen(Ware *Rechnung)
{
FILE *datei_lesen = NULL;
char trennung = " :,;n=";
char zeilen_lesen[256] = {0};
char *formatierer = NULL;
int count = 0;

datei_lesen = fopen("artikel.txt","r");
while(fgets(zeilen_lesen,256,datei_lesen))
{
count++;
}
fclose(datei_lesen);
if(count == 0)
{
return -1;
}
datei_lesen = fopen("artikel.txt","r");
while(fgets(zeilen_lesen,256,datei_lesen))
{
fputs(zeilen_lesen,datei_lesen);
formatierer = strtok(zeilen_lesen,trennung);
if(atoi(formatierer) >= 100000)
{
Rechnung->ANR = atoi(formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->MHD,formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->Bezeichnung,formatierer);
formatierer = strtok(NULL,trennung);
strcpy(Rechnung->VPE,formatierer);
formatierer = strtok(NULL,trennung);
Rechnung->Preis = atoi(formatierer);
Rechnung = realloc(Rechnung,1*sizeof(Ware));
//Rechnung = (Ware*) realloc(Rechnung,1);
Rechnung++;
}
}
fclose(datei_lesen);
return 0;
}


int main(void) {
Ware *Rechnung = (Ware*) malloc(sizeof(Ware));
int test = 0;

initialisiere(&Rechnung);
test = DateiLesen(&Rechnung);
return EXIT_SUCCESS;
}






c pointers struct malloc realloc






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 at 21:39









Yunnosch

11.1k52033




11.1k52033










asked Nov 19 at 21:31









Yondaime Mugiwara

31




31








  • 4




    your signature for the DateiLesen function doesn't match the parameters that you pass in. Do you see any compiler warnings? DateiLesen says it wants a pointer to i.e. a *Ware type, but you have passed in a **Ware type.
    – bruceg
    Nov 19 at 21:36








  • 1




    StackOverflow does not really require perfect English, or I myself would be pretty lost. But please try a little harder to avoid the impression that you cannot be bothered with punctuation, capitalisation only where appropriate and basic grammar. You will not actually insist that you really think "wanna" is correct, will you? Giving instead the impression that you at least tried will give you better reactions. Also even in code, using English words for identifiers will make your question/code easier to understand for the majority of potential answerers.
    – Yunnosch
    Nov 19 at 21:43














  • 4




    your signature for the DateiLesen function doesn't match the parameters that you pass in. Do you see any compiler warnings? DateiLesen says it wants a pointer to i.e. a *Ware type, but you have passed in a **Ware type.
    – bruceg
    Nov 19 at 21:36








  • 1




    StackOverflow does not really require perfect English, or I myself would be pretty lost. But please try a little harder to avoid the impression that you cannot be bothered with punctuation, capitalisation only where appropriate and basic grammar. You will not actually insist that you really think "wanna" is correct, will you? Giving instead the impression that you at least tried will give you better reactions. Also even in code, using English words for identifiers will make your question/code easier to understand for the majority of potential answerers.
    – Yunnosch
    Nov 19 at 21:43








4




4




your signature for the DateiLesen function doesn't match the parameters that you pass in. Do you see any compiler warnings? DateiLesen says it wants a pointer to i.e. a *Ware type, but you have passed in a **Ware type.
– bruceg
Nov 19 at 21:36






your signature for the DateiLesen function doesn't match the parameters that you pass in. Do you see any compiler warnings? DateiLesen says it wants a pointer to i.e. a *Ware type, but you have passed in a **Ware type.
– bruceg
Nov 19 at 21:36






1




1




StackOverflow does not really require perfect English, or I myself would be pretty lost. But please try a little harder to avoid the impression that you cannot be bothered with punctuation, capitalisation only where appropriate and basic grammar. You will not actually insist that you really think "wanna" is correct, will you? Giving instead the impression that you at least tried will give you better reactions. Also even in code, using English words for identifiers will make your question/code easier to understand for the majority of potential answerers.
– Yunnosch
Nov 19 at 21:43




StackOverflow does not really require perfect English, or I myself would be pretty lost. But please try a little harder to avoid the impression that you cannot be bothered with punctuation, capitalisation only where appropriate and basic grammar. You will not actually insist that you really think "wanna" is correct, will you? Giving instead the impression that you at least tried will give you better reactions. Also even in code, using English words for identifiers will make your question/code easier to understand for the majority of potential answerers.
– Yunnosch
Nov 19 at 21:43












1 Answer
1






active

oldest

votes


















0














This is not how you grow an array.



First,



Rechnung++;


is fine and dandy, but Rechnung is no longer a pointer returned by a previous call to malloc or realloc. So you can neither realloc nor free it.



Second,



Rechnung =  realloc(Rechnung,1*sizeof(Ware));


is fine if you want to leave the size of the array always at 1 element no matter what. If you want the size to increase, you need to feed in the new size.



A typical array-growing loop often looks like this:



Data *array = NULL; // note it's fine to realloc a NULL
size_t size = 0;
while (fgets(...)) {
size_t new_size = size + 1;
Data *new_array = realloc(array, sizeof(Data) * new_size);
if (new_array == NULL) {
// report an error, exit, abort, try again, whatever
// note having a separate `new_array` variable allows you
// to retain old data in `array` in the case of `realloc` erroring on you
} else {
array = new_array;
array[size].foo = make_foo();
array[size].bar = make_bar();
size = new_size;
}
}


Note you never increment array because you cannot pass an incremented array to realloc . You cannot also have something like this:



    Data *array = malloc(sizeof(Data));
Data *current = data;
while (...) {
...
current->foo = make_foo();
current->bar = make_bar();
array = realloc(array, sizeof(Data) * new_size);
current++;
}


because realloc may and will return a pointer different from what it was passed, and current will become invalid. So use plain old boring array indexing.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53382931%2frealloc-problems-with-the-old-size%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    This is not how you grow an array.



    First,



    Rechnung++;


    is fine and dandy, but Rechnung is no longer a pointer returned by a previous call to malloc or realloc. So you can neither realloc nor free it.



    Second,



    Rechnung =  realloc(Rechnung,1*sizeof(Ware));


    is fine if you want to leave the size of the array always at 1 element no matter what. If you want the size to increase, you need to feed in the new size.



    A typical array-growing loop often looks like this:



    Data *array = NULL; // note it's fine to realloc a NULL
    size_t size = 0;
    while (fgets(...)) {
    size_t new_size = size + 1;
    Data *new_array = realloc(array, sizeof(Data) * new_size);
    if (new_array == NULL) {
    // report an error, exit, abort, try again, whatever
    // note having a separate `new_array` variable allows you
    // to retain old data in `array` in the case of `realloc` erroring on you
    } else {
    array = new_array;
    array[size].foo = make_foo();
    array[size].bar = make_bar();
    size = new_size;
    }
    }


    Note you never increment array because you cannot pass an incremented array to realloc . You cannot also have something like this:



        Data *array = malloc(sizeof(Data));
    Data *current = data;
    while (...) {
    ...
    current->foo = make_foo();
    current->bar = make_bar();
    array = realloc(array, sizeof(Data) * new_size);
    current++;
    }


    because realloc may and will return a pointer different from what it was passed, and current will become invalid. So use plain old boring array indexing.






    share|improve this answer


























      0














      This is not how you grow an array.



      First,



      Rechnung++;


      is fine and dandy, but Rechnung is no longer a pointer returned by a previous call to malloc or realloc. So you can neither realloc nor free it.



      Second,



      Rechnung =  realloc(Rechnung,1*sizeof(Ware));


      is fine if you want to leave the size of the array always at 1 element no matter what. If you want the size to increase, you need to feed in the new size.



      A typical array-growing loop often looks like this:



      Data *array = NULL; // note it's fine to realloc a NULL
      size_t size = 0;
      while (fgets(...)) {
      size_t new_size = size + 1;
      Data *new_array = realloc(array, sizeof(Data) * new_size);
      if (new_array == NULL) {
      // report an error, exit, abort, try again, whatever
      // note having a separate `new_array` variable allows you
      // to retain old data in `array` in the case of `realloc` erroring on you
      } else {
      array = new_array;
      array[size].foo = make_foo();
      array[size].bar = make_bar();
      size = new_size;
      }
      }


      Note you never increment array because you cannot pass an incremented array to realloc . You cannot also have something like this:



          Data *array = malloc(sizeof(Data));
      Data *current = data;
      while (...) {
      ...
      current->foo = make_foo();
      current->bar = make_bar();
      array = realloc(array, sizeof(Data) * new_size);
      current++;
      }


      because realloc may and will return a pointer different from what it was passed, and current will become invalid. So use plain old boring array indexing.






      share|improve this answer
























        0












        0








        0






        This is not how you grow an array.



        First,



        Rechnung++;


        is fine and dandy, but Rechnung is no longer a pointer returned by a previous call to malloc or realloc. So you can neither realloc nor free it.



        Second,



        Rechnung =  realloc(Rechnung,1*sizeof(Ware));


        is fine if you want to leave the size of the array always at 1 element no matter what. If you want the size to increase, you need to feed in the new size.



        A typical array-growing loop often looks like this:



        Data *array = NULL; // note it's fine to realloc a NULL
        size_t size = 0;
        while (fgets(...)) {
        size_t new_size = size + 1;
        Data *new_array = realloc(array, sizeof(Data) * new_size);
        if (new_array == NULL) {
        // report an error, exit, abort, try again, whatever
        // note having a separate `new_array` variable allows you
        // to retain old data in `array` in the case of `realloc` erroring on you
        } else {
        array = new_array;
        array[size].foo = make_foo();
        array[size].bar = make_bar();
        size = new_size;
        }
        }


        Note you never increment array because you cannot pass an incremented array to realloc . You cannot also have something like this:



            Data *array = malloc(sizeof(Data));
        Data *current = data;
        while (...) {
        ...
        current->foo = make_foo();
        current->bar = make_bar();
        array = realloc(array, sizeof(Data) * new_size);
        current++;
        }


        because realloc may and will return a pointer different from what it was passed, and current will become invalid. So use plain old boring array indexing.






        share|improve this answer












        This is not how you grow an array.



        First,



        Rechnung++;


        is fine and dandy, but Rechnung is no longer a pointer returned by a previous call to malloc or realloc. So you can neither realloc nor free it.



        Second,



        Rechnung =  realloc(Rechnung,1*sizeof(Ware));


        is fine if you want to leave the size of the array always at 1 element no matter what. If you want the size to increase, you need to feed in the new size.



        A typical array-growing loop often looks like this:



        Data *array = NULL; // note it's fine to realloc a NULL
        size_t size = 0;
        while (fgets(...)) {
        size_t new_size = size + 1;
        Data *new_array = realloc(array, sizeof(Data) * new_size);
        if (new_array == NULL) {
        // report an error, exit, abort, try again, whatever
        // note having a separate `new_array` variable allows you
        // to retain old data in `array` in the case of `realloc` erroring on you
        } else {
        array = new_array;
        array[size].foo = make_foo();
        array[size].bar = make_bar();
        size = new_size;
        }
        }


        Note you never increment array because you cannot pass an incremented array to realloc . You cannot also have something like this:



            Data *array = malloc(sizeof(Data));
        Data *current = data;
        while (...) {
        ...
        current->foo = make_foo();
        current->bar = make_bar();
        array = realloc(array, sizeof(Data) * new_size);
        current++;
        }


        because realloc may and will return a pointer different from what it was passed, and current will become invalid. So use plain old boring array indexing.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 19 at 22:13









        n.m.

        71k882166




        71k882166






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53382931%2frealloc-problems-with-the-old-size%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            Origin of the phrase “under your belt”?