Vinay
Vinay

Reputation: 13

Segmentation fault (core dumped) using char*

i am new to c programming. i am getting Segmentation fault (core dumped) when i am
trying to print the string. please help.

#include <stdio.h>
#include <string.h>
int main()
{
  char *ptr;
  strcpy(ptr, "mystring");
  printf( "%s\n", ptr);
 return 0;
}

Upvotes: 1

Views: 3544

Answers (2)

Jav
Jav

Reputation: 1607

When you declare char *ptr;, you allocate memory for a pointer to a char. But if you want to put a string inside the char, it will make an overflow.

Therefore, you have to allocate memory for your string :

char str[1024]; // which is the maximum string lenth that you will be able to put in str.

Furthemore, don't forget the null terminator (\0) that terminate every string and has the size of one char

Upvotes: 1

Mitch Wheat
Mitch Wheat

Reputation: 300549

You haven't allocated any memory for your pointer to point at.

char array[MAX_LEN + 1];

char *ptr = array;

strncpy(ptr, "Cadence", MAX_LEN);
ptr[MAX_LEN] = '\0';

printf( "%s\n", ptr);

Please note that strncpy() can be a safer way to copy strings, since we specify the maximum number of characters to copy, which makes it harder to overrun the string and 'scribble' memory.

Update in response to comments: I've altered the above code to use a slightly safer pattern. You might also want to investigate strlcpy() (non-standard library).

Upvotes: 7

Related Questions