Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old May 28th, 2005, 12:41 AM   #1
tempest
Programming Guru
 
tempest's Avatar
 
Join Date: Oct 2004
Posts: 1,041
Rep Power: 5 tempest is on a distinguished road
Send a message via ICQ to tempest Send a message via AIM to tempest Send a message via Yahoo to tempest
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;
 }
__________________

tempest is offline   Reply With Quote
Old May 28th, 2005, 6:59 AM   #2
Ooble
I eat cake for breakfast.
 
Ooble's Avatar
 
Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9 Ooble is on a distinguished road
First of all, stick a printf() before and after every single statement, and find out which line's buggered. Then post back.
__________________
Me :: You :: Them
Ooble is offline   Reply With Quote
Old May 28th, 2005, 7:08 AM   #3
Nuticulus
Programmer
 
Nuticulus's Avatar
 
Join Date: May 2005
Location: England
Posts: 61
Rep Power: 4 Nuticulus is on a distinguished road
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.
Nuticulus is offline   Reply With Quote
Old May 28th, 2005, 7:26 AM   #4
Ooble
I eat cake for breakfast.
 
Ooble's Avatar
 
Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9 Ooble is on a distinguished road
That's what I was thinking, but I wasn't sure. You have to allocate memory manually before you can deallocate it.
__________________
Me :: You :: Them
Ooble is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 10:52 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC