Home > database >  strcpying a char* into a struct causes EXC_BAD_ACCESS
strcpying a char* into a struct causes EXC_BAD_ACCESS

Time:08-24

I am trying to prototype a window manager thing and in my window struct there is a char* and I am trying to strcpy my variable for the window title into the char* member in my struct but I keep getting an EXC_BAD_ACCESS error and I have no idea how to fix it.

This is my code:

#include <stdio.h>
#include <string.h>

struct window {
    char* title;
    int x;
    int y;
    int w;
    int h;
    void (*drawFunc)(struct window);
};

struct button {
    
};

void* draw(struct window w) {
    printf("hey");
    return (void*)0;
}

int main(int argc, const char* argv[]) {
    struct window w;
    char* title = "hello\0";
    strcpy(w.title, title);
    w.drawFunc = draw(w);
    w.x = 10;
    w.y = 10;
    w.w = 100;
    w.h = 200;
    w.drawFunc(w);
    return 0;
}

CodePudding user response:

Here's fixed code with comment explanations:

int main(int argc, const char* argv[]) {
    struct window w;
    char* title = "hello"; // "" adds \0 at the end automatically 
    w.title = strdup(title); // initialize pointer! needs memory allocation!
    w.drawFunc = draw; // assign function pointer, not function call return value
    ...

Note: strdup is a POSIX standard function,and not in C standard, so you may meed to provide your own implementation, which is trivial:

char *strdup(const char *source) {
    char *result = malloc(strlen(source) 1);
    if(result) strcpy(result, source);
    return result;
}
    
  • Related