开发者

strncpy segfault

I've been having trouble getting this section of code to work. I'm trying to get a character array to be copied so I can get a count of how many tokens there are to dynamically allocate and save them to be examined for environment variables. However, I keep segfaulting when it tries to strncpy the original string.

    void echo(char *str1)
    {
      char *token, *temp;
      char *saveptr1;
      int j, i, k, counter;
      char *copy;

      strncpy(copy, str1, 80);

      const char *delim = " ";
      i = strlen(copy);

      for(j = 0; j 开发者_C百科< i; j++, copy = NULL)
      {
         token = strtok_r(copy, delim, &saveptr1);
         counter++;
         if(token == NULL)
         {
           counter--;
           break;
         }
      }

      // initialize token array for echo
      char *tokAr[counter];
      for(j = 0; j < counter; j++)
        tokAr[j] = malloc(80*sizeof(char));

      for(j = 0, k = 0; j < i; j++, str1 = NULL)
      {
         tokAr[k] = strtok_r(str1, delim, &saveptr1);
         if( tokAr[k] != NULL)
         {
            if(strchr(tokAr[k], 36) != NULL)
            {
              temp = enviro(tokAr[k]);
              printf("%s ", temp);
            }
         else
           printf("%s ", tokAr[k]);
         }
         else
           break;
      }

      for(k = 0; k < counter; k++)
        free(tokAr[k]);
    }

    char* enviro(char *ret)
    {
      char *copy, *expand, *saveptr;
      const char *delim = "$";
      strcpy(copy, ret);
      expand = strtok_r(copy, delim, &saveptr);

      return getenv(expand);
    }

I know it has something to do with how I copy the passed in str1 character array but I can't figure it out from gdb. Any help is greatly appreciated


You haven't allocated memory for copy.

char *copy;
strncpy(copy, str1, 80);

Try malloc or strdup if you don't need the full 81 characters.

copy = malloc(81);
strncpy(copy, str1, 80);

/* Or strdup. */
copy = strdup(str1);


copy does not contain a valid allocated address. Please allocate enough memory with malloc before using copy. Also remember to free copy after you have completed using it to stop memory leak in larger programs.


I think in function echo, you haven't initialized the variable counter and trying to incrementing and decrementing it. Try to do that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜