0

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?

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
  • 2
    `*tasks[0]` is of type `char`. You are assigning an address to it. All bets are off. `tasks[0]=buff` assigns a pointer. Basically this code is a total disaster. You need to step back and get on top of the basics. Don't run before you can walk. Don't cast `malloc` return value. Add error checking. Do `realloc` properly. If it fails, your code leaks. – David Heffernan Feb 02 '14 at 23:30

1 Answers1

1

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().

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
  • thanks both, was told by my lab instructor i was on my own cause i didnt want to learn to code in linux, so im lost. this is the first time ive programmed in C (i have some experience with c++). i think you helped me out more than my teacher ever could. – Charles Finley Feb 02 '14 at 23:47