Search code examples
cpipecallocfile-pointer

Pipe's write overwrites an allocated space of memory


My program it's pretty big, so I'll highlight the main problem and add some details about it.

First part of my code:

int myPipe[2]; //A global variable, so I don't have to pass it to future functions

int main(int argc, char *args[]) 
{
    mode_t pUmask = umask(0000); //Obsolete variable to my problem
    errno = 0; //Obsolete variable to my problem
    char pattern[2500] = "Test1"; //Obsolete variable to my problem
    int p = 0;              //DEFAULT NUMBER OF PROCESSES
    int deep = 0; //Obsolete variable to my problem
    int n = 1; //Obsolete variable to my problem

    if(pipe(myPipe))
    {
        perror("Pipe Error: ");
        exit(-1);
    }
    
    if( (write(myPipe[1], &p, (sizeof(int)*3))) == -1) //First write works
    {
        perror("write: ");
        exit(-1);
    }
    //Then a bunch of code releated to file reading
}

Second part:

{
    //in another function
    //The part where I create fileName
    char* fileName = calloc(strlen(fileData->d_name)+4, sizeof(char));
    strcpy(fileName, fileData->d_name);
}

Third part:

//in another another function
if(S_ISREG(data.st_mode))
{
    printf("\tfileName: %s\n", fileName); //Regular print of the right fileName
    printf("\t\tOh boy! It's a regular.\n");
    printf("\tfileName: %s\n", fileName); //Regular print of the right fileName

    if((read(myPipe[0], &p, (sizeof(int)*3))) == -1) //First time I read
    {
        perror("\t\t read: ");
        exit(-1);
    } 
    printf("fileName: %s", fileName); //SEGMENTATION FAULT

There is a bunch of code in between, but it doesn't affect the fileName at all (in fact, up until the "read", fileName was printed flawlessly), and after it a SEGMENTATION FAULT happens.

At one point by changing the printfs locations I was able to get the fileName AFTER the read, which was basically the fileName value("File1") followed by the p integer value(0), which created the new corrupted fileName("File10").

So what's happening? I reserved the space for fileName, I passed the fileName pointer to the following functions up to that read, and supposedly the fd should have it's own adress space as well. HELP.

P.s. if you need more info, I'm willing to give it to you, even the full code, but it's REALLY complicated, and I think I gave you enough proof that fileName doesn't get corrupted at all until the read part, THANK YOU.

P.p.s. I never close either of the "MyPipe" extremes, since I have to use them multiple times, I wanted to close them at the end of the program.


Solution

  • The statements that write and read the pipe are causing undefined behavior. p is declared:

    int p;
    

    But when you write and read it through the pipe, you use sizeof(int)*3, so you're accessing outside the object.

    Change those statements to use just sizeof p.