Question

I'm writing a little program to order a matrix of strings. In the ordination algorithm I use this function to swap two strings, but in same cases the program crashhes with Segmentation Fault Error. I have understood it's caused by how I inizialize the temp string, but I haven't understood why.

void stringSwap(char*string1,char*string2)
{   const int dim=sizeof(string1);
    char temp[dim];
    strcpy(temp,string1);
    strcpy(string1,string2);
    strcpy(string2,temp);
}

Can someone explain me why it gives this error? And is there another mode to do this thing correctly without using the dinamic allocation that I don't know actually? Thank you very much!

Was it helpful?

Solution

sizeof(string1) is 4 or 8 bytes, depending on your system.

You should use strlen(string1)+1 instead.

OTHER TIPS

string1 is a pointer (not an array, even if arrays are decayed into pointers), and the sizeof some pointer is fixed (it is usually the word size in bytes, e.g. 4 bytes on 32 bits machines, and 8 bytes on 64 bits machines & systems).

The sizeof some pointer is a compile-time constant and does not depend upon the value of that pointer.

This statement

const int dim=sizeof(string1);

will return sizeof of pointer to char that is sizeof( char * ). It is usually equal to either 4 or 8 bytes depending on the platform where you run your program.

I think either the both strings shall have the same size (they can have different actual lengths but sizes shall be equal) and you have to pass that size to the function or this swap function has no sense.

try:

void stringSwap(char*string1,char*string2)
{   
    char temp[strlen(string1)+1];
    strcpy(temp,string1);
    strcpy(string1,string2);
    strcpy(string2,temp);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top