Question

this is just a test code i've been using to figure out how the code works before impelmenting it into my program. basically the same issue happens in both programs, im able to realloc 2 times then it crashes. the final project is a 2d pointer, list length and size lengths. ach of these has to be able to be resized to reasonable limits.

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

int main()
{
    char** tasks;
    char buff[1089];
    int size, i, list_size=1;
    tasks = (char**)malloc(list_size * sizeof(char*));
    printf("input a string!\n");
    gets(buff);
    *tasks[0]=(char*)malloc((strlen(buff)+1));
    tasks[0]=buff;
    printf("%s\n", tasks[0]);

    for (i=1;i<8 ;i++){
        list_size++;
        printf("%d\n", list_size);
        *tasks = realloc(*tasks, list_size* sizeof(char*));
        printf("input a string!\n");
        gets(buff);
        *tasks[i]=(char*)malloc((strlen(buff)+1));
        tasks[i]=buff;
        printf("%s\n", tasks[i]);
    }

    free(tasks);
    return 0;
}

what am i messing up with here?

Était-ce utile?

La solution

Several problems here.

*tasks[0]=(char*)malloc((strlen(buff)+1));

As pointed out by David Heffernan in the comments, you are assigning a pointer to a char. You probably just meant to assign to tasks[0].

tasks[0]=buff;

This is not how you copy a string. You're setting tasks[0] to point to your fixed buffer, and leaking the memory you allocated in the previous step.

*tasks = realloc(*tasks, list_size* sizeof(char*));

This is not a safe way to realloc, and you are also reallocing the wrong pointer (the first entry in the list, rather than the list itself). If the allocation fails, you have lost the original pointer, and leaked that memory. You should realloc to a temporary variable first, like this:

char *temp = realloc(tasks, list_size* sizeof(char*));
if (temp != NULL)
    tasks = temp;

And finally, don't cast the result of malloc().

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top