C segmentation fault-char pointers

℡╲_俬逩灬. 提交于 2019-12-20 07:38:05

问题


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 <stdlib.h>
#include <stdio.h>

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;

};

回答1:


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 a[1];
a[0] = 'a';
encrypt(&a[0]);

Or even just use a single character in your case:

int main(){
  char a = 'a';

  encrypt(&a);
  printf("test:%c/n",a);

  return 0;
};



回答2:


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 buffer[512];
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);



回答3:


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);


来源:https://stackoverflow.com/questions/9658239/c-segmentation-fault-char-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!