cdynamic-memory-allocationc-stringsstring-literalsbus-error

Getting a bus error trying to switch letters in a string


Below is a snippet of my code. My code is supposed to reverse alphabet chars only and skip any special characters. I am currently trying to use "ab-cd" and hope to print "ba-cd", but when I run my code I get a bus error.

I have narrowed down the issue to lines 31 and 32. I malloc'd, but unsure why it will not let me switch chars.

Although it does not show, I will make sure to free the memory using free.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cytype.h> // used for isalpha()

int main(int argc, const char *argv[])
{
    // declaring a pointer of type char to tempString
    char * tempString = (char *)malloc(sizeof(char)* 6);
    tempString = "ab-cd";

    char temp;
    temp = tempString[0];
    tempString[0] = tempString[1];
    tempString[1] = temp;

    printf("%s\n", tempString);

    return 0;
}

Solution

  • The line tempString = "ab-cd"; is not doing what you think it is. Just one line earlier you had stored in tempString the address of an allocated buffer. In this line, however, you store the address of "ab-cd" in tempString. You're not writing to the buffer but rather causing tempString to point somewhere else entirely.

    Specifically, you're directing it a string literal which is stored in a read-only section of memory. Therefore, trying to alter it as you're doing is going to crash your program.

    What you want is to write the string into the buffer you already have. This can be done by

    strcpy(tempString, "ab-cd");
    

    EDIT (thanks to @NateEldredge for catching this):

    Your allocated buffer is not big enough to hold "ab-cd". You need to change the size of the allocation:

    tempString = malloc(sizeof(char)*6);