简体   繁体   中英

Error at execution because of realloc

i wrote a little console program which stores words in an array, represented by
char** test_tab , and then print them.

The program works fine as long as it does not go through the conditional realloc()
(eg if i increase size to 1000 ).
But if realloc() get called the program crashes during the array printing , probably because the memory is messed up in there.

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>

char* get_word();

int main(int argc, char* argv[])
{
    size_t size = 100;
    size_t nb_pointer = 0;
    char** test_tab = malloc(size * sizeof *test_tab);
    char** temp_tab;

    while((*(test_tab + nb_pointer) = get_word()) != NULL)
    {
        nb_pointer++;
        if(nb_pointer >= size)
        {
            size += 100;
            temp_tab = realloc(test_tab, size);

            if(temp_tab != NULL)
                test_tab = temp_tab;
            else
            {
                free(test_tab);
                exit(1);
            }
        }
    }

    for(nb_pointer = 0; *(test_tab + nb_pointer) != NULL; nb_pointer++)
        printf("%s\n", *(test_tab + nb_pointer));

    free(test_tab);

    return 0;
}

Can someone explains me what i am doing wrong right here? Thanks.

The amount of memory in the realloc is not calculated correctly.

       temp_tab = realloc(test_tab, size);

should be

       temp_tab = realloc(test_tab, size * sizeof *test_tab);

Every time you are trying to push one string and at the same time take all the previously pushed string with you. Now string means char * & hence you need to use sizeof(char*) * size & then you need to allocate the memory to the string again to store the actual character.. However you can also approach in this way

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static int size = 0;  // static global means no risk while including this file


char** push(char** memptr, char* data) {
  size++;
  if (size == 1)
    memptr = (char**)malloc(size * sizeof(char*));
  else
    memptr = (char**)realloc(memptr, size* sizeof(char*));

  memptr[size - 1] = (char*)malloc(sizeof(char) * strlen(data) + 1);
  strncpy(memptr[size - 1], data, strlen(data));
  memptr[size - 1][strlen(data) -1] = '\0'; // over writing the `\n` from `fgets`
  return memptr;
}


int main() {
  char buf[1024];
  int i;
  static char** memptr = NULL;
  for (i = 0; i < 5; i++){
    fgets(buf, 1024, stdin);
    memptr = push(memptr, buf);
  }

  for (i = 0; i < size; i++)
    printf("%s\n", memptr[i]);

  return 0;
}

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