Bishal
Bishal

Reputation: 13

"Stack around the variable 'buffer' was corrupted" - What is wrong here

I want to parse the numbers from an IP address which is entered by the user. I have written the following code to take the input IP address from the user and print each bytes of the address.

CODE:(Right now I am assuming that the user input is like "xx.xx.xx.xx")

#include <stdio.h>
#include <string.h>
void main(){

    char ip[16];
    char buffer[6];
    int i=0;
    char temp;
    int len;
    char *ptr1;
    char *ptr2;
    char delim = '.';
    while((temp = getchar()) != '\n')
    {
        ip[i++]=temp;
    }
    ip[i] = '\0';
    ptr2 = ip;
    for(i=0;i<4;i++){
        ptr1 = strchr(ptr2,(int)delim);
        strcpy(buffer,ptr2);
        if(ptr1 != NULL){
            buffer[ptr1-ptr2] = '\0';
            ptr2=ptr1+1;
        }       
        printf("\nString:%s",buffer);
    }


    getchar();

}

The code runs fine but at the end of the running or debugging session it gives the error

Run-Time Check Failure #2 - Stack around the variable 'buffer' was corrupted.

What is the problem with my code?

Upvotes: 1

Views: 2737

Answers (2)

Nishant Kumar
Nishant Kumar

Reputation: 2169

strcpy(buffer,ptr2);

This line is responsible for error. Your buffer size is 6 but ptr2 has more than 6 characters (e.g xx.xx.xx.xx = 12) so it is overflowing it. Increase buffer size. It will solve your problem.

Also Add Array bound checking as suggested by @jonathon. This line ip[i++]=temp; may create problem for larger input.

Upvotes: 6

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

So many problems:

#include <stdio.h>
#include <string.h>
void main(){

    char ip[16];
    char buffer[6];
    int i=0;
    char temp;
    int len;
    char *ptr1;
    char *ptr2;
    char delim = '.';
    while((temp = getchar()) != '\n')
    {
        ip[i++]=temp;            // What is preventing you from writing to ip[16+] ?
    }
    ip[i] = NULL;                // '\0' is the NUL terminator. NULL is a pointer.
    ptr2 = ip;
    for(i=0;i<4;i++){
        ptr1 = strchr(ptr2,(int)delim);
        strcpy(buffer,ptr2);     // Again, you can easily overrun buffer here
        if(ptr1 != NULL){
            buffer[ptr1-ptr2] = '\0';
            ptr2=ptr1+1;
        }       
        printf("\nString:%s",buffer);
    }


    getchar();

}

Upvotes: 2

Related Questions