Reputation: 1183
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 conditionalrealloc()
(e.g 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.
Upvotes: 0
Views: 44
Reputation: 2625
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;
}
Upvotes: 0
Reputation: 33283
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);
Upvotes: 2