![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programming Guru
![]() |
A dreaded "segmentation fault" error :(
In the very beginnings of an encryption program i'm running into an error reallocating memory for a character array... whenever i give it an argument via command-line, i get a segmentation fault.
#include <iostream>
#include <math.h>
char *msg = "I like to encrypt things!";
int main(int argc, char *argv[]) {
if(argc == 2) {
free(msg);
msg = (char *)malloc(sizeof(argv[1]));
strcpy(msg, argv[1]);
}
printf("%s\n", msg);
return 0;
}
__________________
|
|
|
|
|
|
#2 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9
![]() |
First of all, stick a printf() before and after every single statement, and find out which line's buggered. Then post back.
|
|
|
|
|
|
#3 |
|
Programmer
Join Date: May 2005
Location: England
Posts: 61
Rep Power: 4
![]() |
You cannot free that memory pointed to by msg! It has not been allocated by malloc, calloc or realloc, and you cannot free it! That is where your segmentation fault comes from.
__________________
http://www.nuticulus.net/hackmysig/sig.PNG Give my site a chance, you know you want to ;-) Google will solve 99% of your problems. Including those with your sex life. Caution, may <strike>contain</strike> be nuts. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|