Reputation: 783
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
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
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
Reputation: 44240
buffer is uninitialized. Besides &buffer is a pointer to a pointer, not to a character array, as you probably intend.
Upvotes: 1
Reputation: 182629
There are multiple issues in your code. It won't work until you fix all of them
buffer
. Scanf would write into thin air, if it weren't for the next point which is arguably more seriousbuffer
to scanf, not &buffer
input[i]
. You are only allocating
memory for input
.Upvotes: 8