-4

Here is the code I tried:

    void check(char*, int);
int main(){
    int len;
    char* str="stack over flow";
    len=strlen(str);
    check(str,len);
    getch();
    return 0;
}
void check(char* str,int len)
{
    char* arr;int i=0;
    arr=(char*)malloc(sizeof(char)*len);
    arr="over flow stack";
    while(arr[i]!='')
    {
        str[i]=arr[i];//here the error is thrown
        i++;
    }
    puts(str);
}

when I tried to print back elements of arr into str I'm getting error.

shas
  • 703
  • 2
  • 8
  • 31
reciever
  • 69
  • 2
  • 11

2 Answers2

0

You're first allocating memory with malloc, then you're changing that pointer to point to "over flow stack", then you're trying to copy characters from "over flow stack" over the constant string "stack over flow", which has undefined behaviour, thus your program crashes.

0

Using a literal string doesn't allocate any memory - it's being put into the read only space of your program. You can't update this piece of memory.

To get memory you can overwrite you could do something like char* str = strdup("stack over flow");

You're still going to run into issues if the arr in the check function is longer than str

Tibrogargan
  • 4,508
  • 3
  • 19
  • 38