Hi -
1. This was your original (C) code, which crashed with a segmentation fault:
http://www.linuxquestions.org/questi...2/#post4056869
Code:
/*
hey dude error in gnu c pointer please solve this
I am using Red Hat Enterprise Linux 5.0.
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
char * cp = NULL;
cp = (char*)malloc(11);
cp = "abcdefgh";
printf(" cp = %s \n",cp);
free(cp);
return 0;
2. This was my response (to your C) question:
http://www.linuxquestions.org/questi...2/#post4056910
Code:
/*
* Hey, dude - Movie recommendation
*/
...
// 1) Declare character pointer - good!
char * cp = NULL;
// 2) Allocate space to hold up to 10 characters - good!
cp = (char*)malloc(11);
// 3) Assign a static string to the pointer.
// OK .. but you just undid step 2). Why?
// And you just ORPHANED your allocated block - bad. Memory leak!
cp = "abcdefgh";
// 4) Print the string - OK
printf(" cp = %s \n",cp);
// 5) Free the string - bad!
// cp now points to the static string - NOT the allocated block!
free(cp);
...
3. And this is my response to your new, C++ only question:
Code:
#include<iostream>
#include<string>
using namespace std;
main()
{
string s = "rahul";
cout << s << endl;
return 0;
}