Thread: strcat causing string to become empty

  1. #1
    Registered User
    Join Date
    Apr 2012

    strcat causing string to become empty

    I have the following code where strcat is causing problem.
          char* tokens = strtok(buf, "+");
          int n = 0;
          int type = 0;
          char* name = "";
          char* lifetime = "";
          char* data = "";
          for(n=0; tokens!=NULL; n++) {
                type = atoi(tokens);
                name = tokens;
              if(n == 2) {
                 if(type == 1)
                    lifetime = tokens;
                    data = tokens;
              if(n == 3)
                 lifetime = tokens;
              tokens = strtok(NULL, "+");
          if(type == 2) {
             printf("Received Data with Name: %s, Data: \"%s\" and lifetime: %s seconds\n", name, data, lifetime);
             strncat(name, "+", 1);
             printf("Data: %s\n", data);
             strncat(name, data, strlen(data));
             printf("Full Name: %s\n", name);

    In the line where I print the name, data and lifetime everything prints correctly. But after the strcat operations I find that "data" value is empty. After adding debug printf statements I have found that "data" value becomes empty right after
    What could be the reason? Please help.

  2. #2
    Registered User
    Join Date
    Aug 2005
    char* name = "";
    this makes name a string literal. you cannot append anything to that.
    try a char array.

  3. #3
    Registered User
    Join Date
    Jan 2009
    C strings are static arrays of chars, they don't grow or shrink dynamically. Your variable name, is just a pointer you can not use strcat to add characters to it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String.empty v.s. string.null
    By George2 in forum C# Programming
    Replies: 4
    Last Post: 06-19-2008, 08:22 AM
  2. Flush / Empty a string
    By Buzzer in forum C++ Programming
    Replies: 6
    Last Post: 05-15-2006, 01:36 PM
  3. strcat causing segmentation fault?
    By jbsloan in forum C Programming
    Replies: 2
    Last Post: 04-02-2005, 09:42 AM
  4. Tell if a string is empty?
    By dizz in forum C++ Programming
    Replies: 3
    Last Post: 12-10-2002, 12:37 AM
  5. How to empty a string?
    By Zwen in forum C++ Programming
    Replies: 6
    Last Post: 09-30-2002, 07:14 PM

Tags for this Thread

Website Security Test