PHWinfo banniere

Titres
PORTAIL ANNUAIRE ARTICLES COMPARATEUR HÉBERGEURS DEVIS FORUMS RÉDUCTEUR D'URL
Précédent   PHWinfo > Autres forums > Forum Programmation & Conception > comp.lang.cplus > char * call-by-reference problem
S'inscrire FAQ Membres Recherche Messages du jour Marquer les forums comme lus
char * call-by-reference problem

Réponse
 
LinkBack Outils de la discussion
Vieux 04/04/2008, 14h22   #1
Simon K
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut char * call-by-reference problem

When I call
---->>> SetLog("WinMain", Msg("Loading %s ...", filename)); <<---


TCHAR *Msg(TCHAR *szFormat, ...)
{
TCHAR szBuffer[1024]=""; // Large buffer for long filenames or
URLs
const size_t NUMCHARS = sizeof(szBuffer) / sizeof(szBuffer[0]);
const int LASTCHAR = NUMCHARS - 1;

// Format the input string
va_list pArgs;
va_start(pArgs, szFormat);

// Use a bounded buffer size to prevent buffer overruns. Limit
count to
// character size minus one to allow for a NULL terminating
character.
_vsntprintf(szBuffer, NUMCHARS - 1, szFormat, pArgs);
va_end(pArgs);

// Ensure that the formatted string is NULL-terminated
szBuffer[LASTCHAR] = TEXT('\0');

// Display a message box with the formatted string
return szBuffer;
}

void SetLog(TCHAR *ID, TCHAR *szMsg)
{<-----------------------------------------------------szMsg =
szBuffer (of Msg(..))
TCHAR str[BUFSIZE]=""; <------------------------- szMsg reseted!
WHY!?!!!??
TCHAR gt1[BUFSIZE]="", gt2[BUFSIZE]="";
struct tm *newtime;
time_t aclock;
time( &aclock ); // Get time in seconds
newtime = localtime( &aclock ); // Convert time to struct tm form

_tcscpy(gt1, _tasctime(newtime));
_tcsncat(gt2, gt1, _tcslen(gt1)-1);

wsprintf(str, "[%s]%s : %s \n", gt2, ID, szMsg);

AppendText(ghSttEM, str);

FILE *stream = fopen("dc.log","a+");
_ftprintf(stream, str);
fclose(stream);
}




I go through SetLog, it first calls Msg(...) in order to display in
format.

As i debug step by step, I found out some weird problems...
I indicated the problem on the source, can someone tell me what's
going wrong with this code?
  Réponse avec citation
Vieux 04/04/2008, 14h24   #2
Simon K
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: char * call-by-reference problem

On Apr 4, 10:22pm, Simon K <monol...@gmail.com> wrote:
> When I call
> ---->>> SetLog("WinMain", Msg("Loading %s ...", filename)); <<---
>
> TCHAR *Msg(TCHAR *szFormat, ...)
> {
> TCHAR szBuffer[1024]=""; // Large buffer for long filenames or
> URLs
> const size_t NUMCHARS = sizeof(szBuffer) / sizeof(szBuffer[0]);
> const int LASTCHAR = NUMCHARS - 1;
>
> // Format the input string
> va_list pArgs;
> va_start(pArgs, szFormat);
>
> // Use a bounded buffer size to prevent buffer overruns. Limit
> count to
> // character size minus one to allow for a NULL terminating
> character.
> _vsntprintf(szBuffer, NUMCHARS - 1, szFormat, pArgs);
> va_end(pArgs);
>
> // Ensure that the formatted string is NULL-terminated
> szBuffer[LASTCHAR] = TEXT('\0');
>
> // Display a message box with the formatted string
> return szBuffer;
>
> }
>
> void SetLog(TCHAR *ID, TCHAR *szMsg)
> {<-----------------------------------------------------szMsg =
> szBuffer (of Msg(..))
> TCHAR str[BUFSIZE]=""; <------------------------- szMsg reseted!
> WHY!?!!!??
> TCHAR gt1[BUFSIZE]="", gt2[BUFSIZE]="";
> struct tm *newtime;
> time_t aclock;
> time( &aclock ); // Get time in seconds
> newtime = localtime( &aclock ); // Convert time to struct tm form
>
> _tcscpy(gt1, _tasctime(newtime));
> _tcsncat(gt2, gt1, _tcslen(gt1)-1);
>
> wsprintf(str, "[%s]%s : %s \n", gt2, ID, szMsg); ------>> szMsg = str!!! WHY!?!?!?
>
> AppendText(ghSttEM, str);
>
> FILE *stream = fopen("dc.log","a+");
> _ftprintf(stream, str);
> fclose(stream);
>
> }
>
> I go through SetLog, it first calls Msg(...) in order to display in
> format.
>
> As i debug step by step, I found out some weird problems...
> I indicated the problem on the source, can someone tell me what's
> going wrong with this code?


One thing more, I indicated one more problem up here.
  Réponse avec citation
Vieux 04/04/2008, 15h44   #3
Obnoxious User
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: char * call-by-reference problem

On Fri, 04 Apr 2008 06:22:11 -0700, Simon K wrote:

> When I call
> ---->>> SetLog("WinMain", Msg("Loading %s ...", filename)); <<---
>
>
> TCHAR *Msg(TCHAR *szFormat, ...)
> {
> TCHAR szBuffer[1024]=""; // Large buffer for long filenames or
> URLs


Local object.


[snip>
>
> // Display a message box with the formatted string return szBuffer;


I assume there is an actual return statement here, or?
It returns a local object which dies when the function exits.

> }
>
> void SetLog(TCHAR *ID, TCHAR *szMsg)
> {<-----------------------------------------------------szMsg = szBuffer
> (of Msg(..))
> TCHAR str[BUFSIZE]=""; <------------------------- szMsg reseted!
> WHY!?!!!??


Why? Since SetLog() is called directly after Msg() it most likely
overwrites the stack part that Msg() used with its own local object.

[snip]
>
>
>
>
> I go through SetLog, it first calls Msg(...) in order to display in
> format.
>
> As i debug step by step, I found out some weird problems... I indicated
> the problem on the source, can someone tell me what's going wrong with
> this code?


It's written terribly wrong. Compare to this example:

#include <iostream>

int * get_address_to_local_object() {
int local[1024] = {1};
return &local[0];
}

void use_invalid_pointer(int * ptr) {
int local[1024] = {0};
std::cout<<ptr[0]<<std::endl;
}


int main() {
use_invalid_pointer(get_address_to_local_object()) ;
return 0;
}

If you're lucky it will print 0 to illustrate the problem:

:~$ g++ test.cpp
test.cpp: In function ‘int* get_address_to_local_object()’:
test.cpp:4: warning: address of local variable ‘local’ returned
:~$ ./a.out
0
:~$
--
OU

  Réponse avec citation
Vieux 04/04/2008, 16h47   #4
Simon K
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: char * call-by-reference problem

On Apr 4, 11:44 pm, Obnoxious User <O...@127.0.0.1> wrote:
> On Fri, 04 Apr 2008 06:22:11 -0700, Simon K wrote:
> > When I call
> > ---->>> SetLog("WinMain", Msg("Loading %s ...", filename)); <<---

>
> > TCHAR *Msg(TCHAR *szFormat, ...)
> > {
> > TCHAR szBuffer[1024]=""; // Large buffer for long filenames or
> > URLs

>
> Local object.
>
> [snip>
>
>
>
> > // Display a message box with the formatted string return szBuffer;

>
> I assume there is an actual return statement here, or?
> It returns a local object which dies when the function exits.
>
> > }

>
> > void SetLog(TCHAR *ID, TCHAR *szMsg)
> > {<-----------------------------------------------------szMsg = szBuffer
> > (of Msg(..))
> > TCHAR str[BUFSIZE]=""; <------------------------- szMsg reseted!
> > WHY!?!!!??

>
> Why? Since SetLog() is called directly after Msg() it most likely
> overwrites the stack part that Msg() used with its own local object.
>
> [snip]
>
>
>
> > I go through SetLog, it first calls Msg(...) in order to display in
> > format.

>
> > As i debug step by step, I found out some weird problems... I indicated
> > the problem on the source, can someone tell me what's going wrong with
> > this code?

>
> It's written terribly wrong. Compare to this example:
>
> #include <iostream>
>
> int * get_address_to_local_object() {
> int local[1024] = {1};
> return &local[0];
>
> }
>
> void use_invalid_pointer(int * ptr) {
> int local[1024] = {0};
> std::cout<<ptr[0]<<std::endl;
>
> }
>
> int main() {
> use_invalid_pointer(get_address_to_local_object()) ;
> return 0;
>
> }
>
> If you're lucky it will print 0 to illustrate the problem:
>
> :~$ g++ test.cpp
> test.cpp: In function 'int* get_address_to_local_object()':
> test.cpp:4: warning: address of local variable 'local' returned
> :~$ ./a.out
> 0
> :~$
> --
> OU


I just looked up to find out what was wrong, exactly what u said.
Thou, I can't figure out how to solve this problem.
  Réponse avec citation
Vieux 04/04/2008, 17h15   #5
Simon K
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: char * call-by-reference problem

It looks really stupid to answer my own question but I just found out
one solution

In Msg,

TCHAR *Msg(TCHAR *szFormat, ...)
{
TCHAR szBuffer[1024]=""; // Large buffer for long filenames or
URLs


I changed

TCHAR szBuffer[1024]=""; ==> static TCHAR szBuffer[1024]="";

and added one more line,
ZeroMemory(szBuffer, sizeof(szBuffer));

in order to reset szBuffer everytime I get thru Msg.


Well, I don't think this is a firm solution, any better idea?
  Réponse avec citation
Vieux 04/04/2008, 20h23   #6
Obnoxious User
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: char * call-by-reference problem


[Please quote some context.]

On Fri, 04 Apr 2008 09:15:02 -0700, Simon K wrote:
> It looks really stupid to answer my own question but I just found out
> one solution
>
> In Msg,
>
> TCHAR *Msg(TCHAR *szFormat, ...)
> {
> TCHAR szBuffer[1024]=""; // Large buffer for long filenames or
> URLs
>
>
> I changed
>
> TCHAR szBuffer[1024]=""; ==> static TCHAR szBuffer[1024]="";
>
> and added one more line,
> ZeroMemory(szBuffer, sizeof(szBuffer));


Unnecessary.

>
> in order to reset szBuffer everytime I get thru Msg.


int written = _vsntprintf(szBuffer, NUMCHARS - 1, szFormat, pArgs);
if(written == -1) throw "error";
szBuffer[written] = 0;

>
>
> Well, I don't think this is a firm solution, any better idea?


boost::shared_ptr<>, std::string, std::vector, so many options

And what about this situation:

TCHAR * m1 = Msg("Loading %s ...", filename);
TCHAR * m2 = Msg("Loading %s ...", filename);

SetLog("WinMain", m1);
SetLog("WinMain", m2);

--
OU
  Réponse avec citation
Réponse


Outils de la discussion

Règles de messages
Vous ne pouvez pas créer de nouvelles discussions
Vous ne pouvez pas envoyer des réponses
Vous ne pouvez pas envoyer des pièces jointes
Vous ne pouvez pas modifier vos messages

Les balises BB sont activées : oui
Les smileys sont activés : oui
La balise [IMG] est activée : oui
Le code HTML peut être employé : non
Trackbacks are oui
Pingbacks are oui
Refbacks are oui


Fuseau horaire GMT +1. Il est actuellement 07h30.


Édité par : vBulletin® version 3.7.2
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0 RC5 Tous droits réservés.
Version française #16 par l'association vBulletin francophone
PHWinfo est un site Éducation Sans Frontières
Ad Management by RedTyger
©Tous droits réservés par les parties respectives
Page generated in 0,13525 seconds with 14 queries