2

I am new to C programming and I am unable to figure out why this is happening.

char *example(char *temp) {
      char *xyz;
      memset(xyz,0,strlen(temp));
      strncpy(xyz,temp,3);
      strcat(xyz,"XX);
      return xyz;
      }

int main() {
      char temp[] = "ABCDEF"
      char *xyz;
      xyz = example(temp);
      printf("Returned string is: %s",xyz);
      return 0;
      }

I just want to know what all I am doing wrong cause I tried to run GDB and it showed I am trying to access some unreachable part of memory but am not able to figure it out. Thanks in advance.

2 Answers 2

6

The problem is here:

char *xyz;
memset(xyz,0,strlen(temp));

You never initialized xyz. Therefore it's an invalid pointer.

What you need to do it allocate something for it:

char *xyz = malloc(strlen(temp) + 1);   //  Allocate, +1 is for the '\0'.
memset(xyz,0,strlen(temp));

and free it when you're done with it:

int main() {
    char temp[] = "ABCDEF"
    char *xyz;
    xyz = example(temp);
    printf("Returned string is: %s",xyz);

    free(xyz);   //  Free

    return 0;
}

EDIT : Other problems:

These 3 lines here are very dangerous:

  memset(xyz,0,strlen(temp));
  strncpy(xyz,temp,3);   //  The nul is not copied in strncpy.
  xyz[3] = '\0';         //  Add the nul manually.
  strcat(xyz,"XX");      //  You need to ensure that xyz is large enough.
3
  • He's also doing dangerous things with strcat and the like, you might want to mention that. Commented Nov 16, 2011 at 2:35
  • NULL (with two l's) usually refers to the pointer, while nul usually refers to the ASCII character.
    – Chris Lutz
    Commented Nov 16, 2011 at 2:38
  • Thanks, that is awesome!! I was being a dumbass not initializing the pointer. Perfect!!!
    – noMAD
    Commented Nov 16, 2011 at 2:47
0

xyz is uninitialized in your code, and you just copy the string 'temp' to a random memory location in 'example'. You would need to allocate it first, i.e. xyz = malloc(strlen(temp) + 1);

Not the answer you're looking for? Browse other questions tagged or ask your own question.