0
#include <stdio.h>
int main(){
   printf("asd");
return 0;
}

The task is without modifying this program, overwriting or using define, in windows environment, this program have to write out : Yourname asd Yourname. Any idea?

4
  • Write a program that prints "Yourname", runs your program, then prints "Yourname". Simples! Commented Oct 6, 2015 at 10:13
  • You can redefine printf as malloc was redefined in this answer. Commented Oct 6, 2015 at 10:18
  • OP is not allowed to use #define Commented Oct 6, 2015 at 10:24
  • @Bathsheba my choice of words was not clear, in that answer there is no #define, only redeclarations of the functions. Commented Oct 6, 2015 at 10:26

2 Answers 2

1

You can do it like this (edited to read Yourname from stdin):

#include <stdio.h>
#include <string.h>
int main(){
    printf("asd");
    return 0;
}

int printf(const char *__restrict __format, ...)
{
    char str[106], scs[50];
    scanf("%s", &scs);
    strcpy(str,scs);
    puts(strcat(strcat(strcat(strcat(str," "), __format)," "),scs));
    return 1;
}

Here's a working demo.

Sign up to request clarification or add additional context in comments.

4 Comments

But in your code you are overwriting the printf's function
@GáborRuszcsák yes, but you're not overriding the main function... I believe the task asked not to override the program but didn't say anything about overriding base functions in C.
This is a good answer. Plus one. It would be even better if you were to explain how you can get away with replacing printf, in the context of the one definition rule (as your linked answer in the comment does).
@Bathsheba thanks, I believe I got away with it in the same manner as this guy got away with it when he replaced malloc ;) I'm not sure about the inner workings though...
0

You can do it in a simple way. Global objects are created on the static memory area, they are allocated and initialized before the execution of main, and are freed after the execution of main. Here's the simple answer to your problem:

#include<iostream>

struct MyName {
public: 
    MyName() { printf("%s", "GaborRuszcsak\n"); }
    ~MyName() { printf("%s", "\nGaborRuszcsak\n"); }
};

MyName isGaborRuszcsak;

int main(int argc, char** argv){
    printf("asd");
    return 0;
}

Hope that helps.

2 Comments

Your code does not compile, can you please fix it and test it here?
the only thing is: his code is in C, not C++ (#include <stdio.h>).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.