Curnelious Curnelious - 6 months ago 53
C Question

Passing pointer and copy value

I guess I do something stupid here, please help me understand what it is, i get a crash :

char *data="xyz";
int EEIndex=0;
int getEEPROMindex();
void updateEEPROMindex();
void getCmd(char *cmd);
void getcmdAtIndex(int index,char *cmd);

int main(int argc, const char * argv[]) {

printf("%s ",data );
return 0 ;

void getCmd(char *cmd)
getcmdAtIndex(EEIndex, cmd);

void getcmdAtIndex(int index,char *cmd)
char *EEPROM[]={"A","E","C","D"};

strcpy(cmd, EEPROM[index]);



It's customary to make string literals read-only. That is:

char *data="xyz";

when your code tried to change the bytes x, y and z, the OS crashes it.

To make it writable, replace a pointer with an array; you should also specify the size of the array. The easiest method to do it is:

char data[] = "xyz"; // will hold a maximum of 3 bytes (size is implicit)


char data[20]; // will hold a maximum of 19 bytes plus an end-of-string byte

You can also use strdup:

char* data;
strdup(cmd, EEPROM[index]); // instead of strcpy

but this involves dynamic memory allocation, which I think you don't want to bother with.