Thread: strcpy crashes program when used with a char pointer.

  1. #1
    Registered User
    Join Date
    Nov 2016
    Posts
    18

    strcpy crashes program when used with a char pointer.

    the title says it all.
    here's an example code i tested too:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    char * str;
    
    int main( void )
    {
    
        strcpy(str, "Hello World!");
    
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    str is just a pointer. It has no space to hold the string. What you want is a char array with at least enough space to hold the characters (including the null terminating character), and it may as well be declared inside main.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
        char str[100];
        strcpy(str, "Hello World!");
        printf("%s\n", str);
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 03-22-2016, 10:45 AM
  2. Converting char to char*, strcpy problems
    By Gareth321 in forum C Programming
    Replies: 9
    Last Post: 05-24-2011, 12:23 AM
  3. Problems coping a char to a char using strcpy
    By iKlys++ in forum C++ Programming
    Replies: 3
    Last Post: 02-10-2011, 06:39 PM
  4. Replies: 8
    Last Post: 07-18-2005, 05:53 AM
  5. two strcpy-ies crashes my program
    By Jakob in forum C++ Programming
    Replies: 3
    Last Post: 03-28-2005, 07:17 AM

Tags for this Thread