Up vote 0 down vote favorite share g+ share fb share tw.
I need help figuring out why I am getting a segmentation fault here. I have gone over it and I think I am doing something wrong with the pointers, but I can figure out what. My Program: #include #include void encrypt(char* c); //characters are shifted by 175 int main(){ char* a; *a = 'a'; /*SEGMENTATION FAULT HERE!
*/ encrypt(a); printf("test:%c/n",*a); return 0; }; void encrypt(char* c){ char* result; int i=(int)(*c); i+=175; if(i>255) { i-=256; } *c=(char)i; }; c encryption segmentation-fault link|improve this question asked Mar 11 at 19:38spatara635 100% accept rate.
2 Welcome to StackOverflow. Please note that the preferred way of saying 'thanks' around here is by up-voting good questions and helpful answers (once you have enough reputation to do so), and by accepting the most helpful answer to any question you ask (which also gives you a small boost to your reputation). Please see the FAQ and especially How do I ask questions here?
– Jonathan Leffler Mar 11 at 19:41.
The problem is here: char *a; *a = 'a' Since the variable "a" is not initialized, *a = 'a' is assigning to a random memory location. You could do something like this: char a1; a0 = 'a'; encrypt(&a0); Or even just use a single character in your case: int main(){ char a = 'a'; encrypt(&a); printf("test:%c/n",a); return 0; }.
That worked! Thanks! – spatara Mar 11 at 19:46.
Char* a; *a = 'a'; /*SEGMENTATION FAULT HERE! */ There isn't any "there" there. You've declared a and left it uninitialized.
Then you tried to use it as an address. You need to make a point to something. One example: char buffer512; char *a = buffer; (Note buffer has a maximum size and when it falls out of scope you cannot reference any pointers to it.
) Or dynamic memory: char *a = malloc(/* Some size... */); if (!a) { /* TODO: handle memory allocation failure */ } // todo - do something with a. Free(a).
That pointer a does not get the actual space where to store the data. You just declare the pointer, but pointing to where? You can assign memory this way: char *a = malloc(1); Then it won't segfault.
You have to free the variable afterwards: free(a); But in this case, even better, char a = 'a'; encript(&a).
Malloc(1) seems like a heavy-weight way of dealing with this particular example. – Jonathan Leffler Mar 11 at 19:45 Yes, well, you're right. Just wanted to show some patterns for assigning dynamic memory.
– Diego Sevilla Mar 11 at 19:45 Thanks! This is also a good solution :) – spatara Mar 11 at 19:47.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.