0

In the following code, I keep crashing after the last for-loop. I can't figure out by debugging with Netbeans.. The for loop works, and prints what I want to be printed but then the program crashes instead of succesfull termination. Could you please help (I know about gets, I will try fgets soon)??

Code:

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


int main()
{
    char *str,**string,buffer[50],temp[2];
    int i,j,size,counter;
    size=1;

    string=(char**) calloc(size,sizeof(char*));
    for (i=0; i<size; i++) string[i]=(char*)malloc(50*sizeof(char));

    printf("\nGimme strings, terminate input with x");
    i=0;
    gets(string[i]);
    temp[0]=120;//x
    temp[1]='\0';
    size=2;
    while(strcmp(string[i],temp)!=0)
    {
        string=realloc(string,size*sizeof(char**));
        i++;
        string[i]=malloc(50*sizeof(char));
        gets(string[i]);
        size++;
        counter++;
    }
    for(i=0; i<=counter; i++) printf("\n%s",string[i]);
    return 0;
}
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
alex777
  • 167
  • 5
  • 14

2 Answers2

1

counter is not initiated to 0 before the while loop

And use

string=realloc(string,size*sizeof(char*));

instead of

string=realloc(string,size*sizeof(char**));

Could you describe in detail what you intend to do because in your code you are allocating array of pointers and then you allocate memory for each pointer in the array and then you remove the almost of the array with realloc(string,2*sizeof(char**)); this will remove almost the array and keep only the first 2 pointers. so with this you are loosing pointers to allocated memory so you could not free them any more:

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
0
  1. Counter should be set to zero before the while cycle. It is not set to zero by default.

  2. The cycle in the for look should exclude counter:

    for(i=0; i<counter; i++) printf("\n%s",string[i]);

  3. Free all dynamically allocated memory by calling free.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176