suenda
suenda

Reputation: 783

Dynamic Array of char Pointer

I am trying to define a dynamic array containing char pointers that point to strings. The string can be of any length, so i used char pointers. I want to dynamically resize the array each time I need to store more values. The following code gives me segmentation fault. Am I doing it well?

int main() {
    char **input=NULL;
    char *buffer;

    int i=0;

    do {
        input = (char **)realloc(input, (i+1) * sizeof(char *));

        scanf("%s", &buffer);
        strcpy(input[i++],buffer);

    } while(strlen(buffer)!=0);


}

Upvotes: 1

Views: 2078

Answers (5)

hmjd
hmjd

Reputation: 121961

In addition to the issues already listed in the other answers the loop will never terminate as:

scanf("%s", buffer);

will not return until it reads at least one character, excluding the end of line character.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

The problem is that you define buffer as a pointer, but you do not point it to something that can hold the scanned string, so scanf writes out in unallocated memory which is really bad. You also do not allocate input[i] so strcpy will also fail. You might want to change that to use strdup instead:

input[i++] = strdup(buffer);

Another couple of nitpicks: When scanning for a string, you do not need the & on the string buffer, so redo like this:

scanf("%s", buffer);

And you should not cast the result of realloc (or malloc either for that matter):

input = realloc(input, (i+1) * sizeof(char *));

Upvotes: 1

wildplasser
wildplasser

Reputation: 44240

buffer is uninitialized. Besides &buffer is a pointer to a pointer, not to a character array, as you probably intend.

Upvotes: 1

ziu
ziu

Reputation: 2720

Your buffer and your input[i] are not allocated.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182629

There are multiple issues in your code. It won't work until you fix all of them

  • You aren't allocating memory for buffer. Scanf would write into thin air, if it weren't for the next point which is arguably more serious
  • You should pass buffer to scanf, not &buffer
  • You aren't allocating memory for input[i]. You are only allocating memory for input.

Upvotes: 8

Related Questions