I need some help on this.... The first assignment is to show how the printf stat
ID: 3820804 • Letter: I
Question
I need some help on this....
The first assignment is to show how the printf statement determines the end of a string. Using this code segment in your code:
char* ptr = my_malloc(6*sizeof(char));
memcpy(ptr, "Hello ", 6*sizeof(char));
printf("%s", ptr);
The output should look like:
Hello
(Some other characters)
The second example of demonstrating the similar effect is:
------------------------------
char my_str[27];
strcpy(my_str, "abcdefghijklmnopqrstuvwxyz";
printf("original long output: %s ", my_str);
strcpy(my_str, "123456789");
printf("short output: %s ", my_str);
my_str[9] = '9';
printf("final output: %s ", my_str);
------------------------------
Lastly, the gcc command which disable the stack protector is:
gcc -fno-stack-protector example.c
Explanation / Answer
#include <stdio.h>
#include <string.h>
static unsigned char our_memory[1024 * 1024]; //reserve 1 MB for malloc
static size_t next_index = 0;
void * mymalloc(size_t sz)
{
void *mem;
if(sizeof our_memory - next_index < sz)
return NULL;
mem = &our_memory[next_index];
next_index += sz;
return mem;
}
int main(int argc, char const *argv[])
{
char* ptr = (char*)mymalloc(6*sizeof(char));
memcpy(ptr, "Hello ", 6*sizeof(char));
printf("%s", ptr);
return 0;
}
==============================================================
Output:
akshay@akshay-Inspiron-3537:~/Chegg$ gcc -fno-stack-protector test.c
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
Hello
======================================================================
Peogram 2
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char my_str[27];
strcpy(my_str, "abcdefghijklmnopqrstuvwxyz");
printf("original long output: %s ", my_str);
strcpy(my_str, "123456789");
printf("short output: %s ", my_str);
my_str[9] = '9';
printf("final output: %s ", my_str);
return 0;
}
======================================================================
akshay@akshay-Inspiron-3537:~/Chegg$ gcc -fno-stack-protector test.c
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
original long output: abcdefghijklmnopqrstuvwxyz
short output: 123456789
final output: 1234567899klmnopqrstuvwxyz