1 Replies - 898 Views - Last Post: 28 March 2014 - 12:12 PM Rate Topic: -----

#1 xfmym   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 20-January 14

Pointer issue, bus error 10.... overwriting string literals...

Posted 28 March 2014 - 12:07 PM

So I am trying to take a string and replace a certain character with another in the string. The function doesn't
return anything, but rather changes the string itself. Why would I be getting a bus error 10?

void replaceChar(char *src, char oldChar, char newChar){
    //get length of source string.
    int length = 0;
    length = (int) strlen(src);
    
    char *newSrc = (char *)malloc((length + 1) * sizeof(char));
    
    //checks and manipulates the string.
    int i;
    char c;
    for (i = 0; i < length; i++){
        if (src[i] == oldChar){
            src[i] = newChar;
        }
    }
}


I feel like maybe I can't overwrite existing characters in a string, but I don't know how else to implement this without returning anything, which I am not allowed to do.

Is This A Good Question/Topic? 0
  • +

Replies To: Pointer issue, bus error 10.... overwriting string literals...

#2 sepp2k   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2770
  • View blog
  • Posts: 4,429
  • Joined: 21-June 11

Re: Pointer issue, bus error 10.... overwriting string literals...

Posted 28 March 2014 - 12:12 PM

Why do you allocate new memory if you just override the old one? You also never use the variable c.

Anyway, I suspect that your problem isn't with the code you've shown us, but with how you call it. Are you calling it with a string literal as the argument by any chance? String literals may not be modified and are often stored in read-only memory.

This post has been edited by sepp2k: 28 March 2014 - 12:13 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1