-2

I wrote this C code:

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

int main()
{
  char *i, *p, *p1="Hello";
  strcpy(p,p1);  //The first strcpy works.
  printf("%s\n", p); //show copy successful
  printf("Please hit a key to continue....\n");
  getchar();
  strcpy(i,p); //The second strcpy causes stop working problem. Why?
  printf("%s\n", i);
  return 0;
}

Can anyone tell me why the second strcpy doesn't work?

Kai
  • 5,850
  • 13
  • 43
  • 63
Steve
  • 7
  • 2

3 Answers3

2

I would say you were lucky the first strcpy worked in the first place! You basically declared a POINTER to a char, nothing else. What you need in order for strcpy to work correctly is make sure you have an array of char large enough to fit your copy in. In other words, allocate some memory first for your pointer, or use an array...

1

you need to allocate memory for the chars. you could e.g. do it like this:

char* p1 = "Hello";
char* i  = (char*)malloc(sizeof(char) * 6);   
char* p  = (char*)malloc(sizeof(char) * 6);     

please don't miss a free afterwards (before return):

free(p);
free(i);

Moreover an additional include is needed to use malloc and free:

#include<stdlib.h>

Your complete sample should be looking like this:

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

int main()
{ 
  char* p1 = "Hello";
  char* i  = (char*)malloc(sizeof(char) * 6);   
  char* p  = (char*)malloc(sizeof(char) * 6);   

  // 1st copy
  strcpy(p,p1);
  printf("1st copy: %s\n", p);

  // 2nd copy
  strcpy(i,p);
  printf("2nd copy: %s\n", i);

  getchar();

  // free prior allocated memory
  free(p);
  free(i);

  return 0;
}
Kai
  • 5,850
  • 13
  • 43
  • 63
0

The problem is that strcpy won't allocate memory for your string hence it will most likely crash if you haven't done so. I'd say its by chance the first instance works.

You're lucky the program only gives you a segmentation fault. You can either allocate memory using malloc or calloc or you use the function strdup to allocate memory for you.

 char *i, *p, *p1="Hello";
 p = strdup(p1);
 printf("%s\n", p); //show copy successful
 printf("Please hit a key to continue....\n");
 getchar();
 i = strdup(p);
 printf("%s\n", i);
 free(p);
 free(i);

Don't forget to free the memory afterwards!

Linus
  • 1,516
  • 17
  • 35
  • Thanks for the reply. Just a question about free(). Is the memory still occupied without free() if the program is closed? I assume the memory all released when an application is quitted. If I stored a string to a struct member using strdup(), do I still need to release it before closing the app? Thanks! – Steve Oct 29 '15 at 03:03
  • @Steve unless you're using a *very* old compiler the memory is always freed. However it is not good practise to rely on this fact. See http://stackoverflow.com/questions/654754/what-really-happens-when-you-dont-free-after-malloc for details. – Linus Oct 29 '15 at 09:03