Question:
Segmentation fault in C++ code (NetBeans 7.1.2)?
2013-05-09 22:10:05 UTC
Hi All,

I am new to C/C++ development in Netbeans. I encountered following problem.
I am doing some pointer operations in my code n then memcpy() sample code is as follows.
................................

char * dest;

int nValue= toPointer - fromPointer;

dest = malloc(nValue+1);

memset(dest,0,nValue+1);

memcpy(dest,fromPointer,nValue);

dest[nValue]='\0';

...............................
when i am running my application , it is crashing just after memset().

To avoid crash i have done following changes.

1. Value of nValue is always greater than 0 also i have added NULL checks to ensure that fromPointer and dest are not NULL.

2. Instead of memcpy I used for loop to copy the content character by character

With both changes application still crashed with same error message... error message is as follows

/cygdrive/E/Program Files/NetBeans 7.2.1/ide/bin/nativeexecution/dorun.sh: line 33: 2864 segmentation fault sh "${SHFILE}"

Any suggestion to avoid this crash ?
Three answers:
husoski
2013-05-09 22:43:11 UTC
You didn't say which line was blowing up. I'll guess that it's the memcpy() call because (1) a nonzero return value from malloc is always a valid pointer. If everything is as you say, then it would seem that fromPointer must be invalid. If you haven't figured out how to use the debugger, you can find out where the fail is by inserting cout<<"got here"<


It's not enough for fromPointer to be nonzero. It really must be a legally-obtained pointer to a C/C++ data object. Also, for pointer subtraction to be defined, both fromPointer and toPointer point to elements of the same array.



By the way, that memset() call has no effect, since every 0 it writes is overwritten by the memcpy() and assignment that follow.



Also, this is C, not C++ code. C++ doesn't allow that dest = malloc(nValue+1); line. That assigns a void* pointer to a char* pointer. That's legal C (though it may generate a warning on some compilers) but C++ flatly requires an error in that case. You need to cast the result of malloc() in a C++ program:

dest = (char*) malloc(nValue+1);
2016-12-01 09:26:55 UTC
You did not say which line replaced into blowing up. i'm going to wager that it is the memcpy() call through fact (a million) a nonzero return fee from malloc is usually a valid pointer. If each little thing is as you're saying, then it would look that fromPointer might desire to be invalid. in case you have not discovered the thank you to apply the debugger, you will stumble on out the place the fail is with the help of putting cout<<"have been given right here"<
?
2016-12-12 15:49:36 UTC
Netbeans 7.1.2


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...