Reputation:
I just wanted to try out this code...
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main() {
char *outFile1 = NULL;
char *outFile2 = NULL;
cout << "HI";
outFile1 = "//tmp//Softwares//v//vdisk";
strcpy(outFile2, outFile1);
cout << "HI";
}
If I run this code... nothing gets printed. and if I comment the "strcpy(outFile2, outFile1);"... both the "HI" gets printed. Why is this t case?. It doesnt throw me any error though.
Upvotes: 0
Views: 143
Reputation: 25053
You're writing to an invalid location. Your program is crashing silently on the strcpy()
. The first HI
doesn't print since the output is buffered. If you change the first cout to this:
cout << "HI" << endl;
...you'll probably get it.
As for why your program is crashing, this puts the address of a string into outfile1
:
outFile1 = "//tmp//Softwares//v//vdisk";
This copies that string to location zero, which (depending on the OS) would normally kill your program:
strcpy(outFile2, outFile1);
Upvotes: 5
Reputation: 703
A few problems with your code, one the char string outFile2 has not been allocated, so your program is probably corrupting the stack and preventing the output from being properly displayed.
Try using allocating some memory using malloc() to hold the string that you want to copy, or look into using the C++ std String class (http://www.cplusplus.com/reference/string/string/). The C memory allocation would be something like,
int slen=strlen(outFile1)+1;
outFile2 = (char *)malloc(sizeof(char)*slen);
strncpy(outFile2, outFile1, slen);
Upvotes: 0
Reputation: 1903
There is no memory allocated for either string. You just set a pointer to the string literal "//tmp//Softwares//v//vdisk". Now when you go to copy it from outFile1 to outFile2 you are most likely overwriting stuff you shouldn't be or for some reason strcpy is causing issues elsewhere (hard to tell since it's undefined). That's just a guess though.
Upvotes: 1