Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Meet and Greet (http://www.go4expert.com/community/meet-and-greet/)
-   -   Segfault when using Pointer to pointer (http://www.go4expert.com/community/segfault-using-pointer-pointer-t28756/)

shree249 20Jul2012 15:29

Segfault when using Pointer to pointer
 
Hi, I am writing a c++ code which uses a pointer to pointer of type char*. I get a segfault while executing it.
When i replace the pointer to pointer variable with array of pointer variable it works. i.e when i use char **var i get a segfault, but when i use char *var[51] the code works as expected. as per my limited knowledge char **var and char *var[51] mean the same thing only the difference being the former does not have a limit.

The code is given below. This code basically scans a file named filename.txt and matches a line and stores the address of the IP string in pointer to pointer.
The contents of the file is
**********
user@servername:~$ cat filename.txt
order deny,allow
deny from all
allow from 1.2.3.4 9.8.7.6 22.33.44.55
**********
Code:

#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char *argv[])
{
        char *requestip;
        requestip = "1.2.3.4";
        printf("%s\n", requestip);

        char *ipstring,*token;
        char **ips;
        int j,count;
        int foundline;
        foundline=0;
        count=0;

        char tmp_line[1024];
        FILE *fp = fopen("filename.txt", "r");
        if(fp == NULL)      return 1;
        while(fgets(tmp_line,1023,fp)!=0)      {
                if(strcasestr(tmp_line,"order deny,allow"))  {      foundline=1;  continue;      }
                if(foundline==1)                              {      if(strcasestr(tmp_line,"deny from all")==NULL)  return 0;      foundline++; continue;}

                if(foundline==2)        {
                        foundline++;
                        ipstring = strcasestr(tmp_line,"allow from");
                        if(ipstring != NULL)    {
                                ipstring=ipstring+11;
                                ipstring=strdup(ipstring);
                                for (j=0;;j++,ipstring=NULL)    {
                                        token = strtok(ipstring," ");
                                        if (token == NULL) break;
                                        printf("%s\n",token);
                                        ips[j] = token;
                                        count=j;
                                }
                                break;
                        }
                        else    return 0;
                }
                if(!feof(fp)) break;
        }

        exit(EXIT_SUCCESS);
}

Please let me know if i am doing anything wrong.
gcc version 4.5.2 (GCC)
OS: slackware 13


All times are GMT +5.5. The time now is 10:11.