0

I have try set one of array item to specific value. The program is compiled but when I execute it return segfault.

Here is the code:

#include <stdio.h>

void Debug(unsigned char* str, char simbol, char size);


int main() {

  Debug((unsigned char*)"DEBUG: message: x\r\n", 'e', 40);
  return(0);

}

//this function I try to replace all occurrences of x with simbol value 'e'

void Debug (unsigned char* str, char simbol, char size){
    char i;

    for (i = 0 ; i < size ; i++){
        if( str[i] == 'x' ){
            str[i] = simbol;
        }
    }
    printf ("%s\n",  str);
}

Thanks in advance for any help !

Gopi
  • 19,784
  • 4
  • 24
  • 36
  • #include #include void Debug(unsigned char* str, char simbol, char size); int main() { unsigned char * mumu; mumu = malloc(sizeof(unsigned char)*40); mumu = "DEBUG: message: x\r\n"; Debug(mumu, 'e', 40); return(0); } void Debug (unsigned char* str, char simbol, char size){ int i; unsigned char * mumu2; mumu2 = malloc(sizeof(unsigned char)*40); strcpy(mumu2,str); for (i = 0 ; i < size ; i++){ if( str[i] == 'x' ){ mumu2[i] = simbol; }} printf ("%s\n", mumu2); return; } THIS IS A WORKING CODE – Dimitri Feb 13 '15 at 09:57

2 Answers2

0
unsigned char* str

Here str is read-only and you are trying to write to this location hence segmentation fault.

Have a array

unsigned char str[100] = "DEBUG: message: x\r\n";

and pass this array to the function.

Gopi
  • 19,784
  • 4
  • 24
  • 36
0

You try to modify a const object (the string). This is the reason, why you had to cast the string to unsigned char* in the first place. To solve this,you have to copy that string into a char array first.

MikeMB
  • 20,029
  • 9
  • 57
  • 102