读取(不写入)坏指针会导致程序崩溃吗? [英] Can reading (not writing) a bad pointer cause the program to crash later ?

查看:100
本文介绍了读取(不写入)坏指针会导致程序崩溃吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,


让我们假设以下代码:

Hello,

Let?s assume the following piece of code :


void f9( )

{

char * c ="无法执行f9" ;;

抛出c;

}


试试

{

f9();

}

catch(char * c)

{

char message [4096];

sprintf(message," Exception:%s", c);

cout<<消息;

}
void f9 ()
{
char* c= "Could not execute f9";
throw c;
}

try
{
f9 ();
}
catch (char* c)
{
char message[4096];
sprintf (message, "Exception : %s", c);
cout << message;
}



此代码工作正常,输出为:例外:无法执行f9。


尽管如此,在catch子句中,指针c是不确定的,指针可能已经丢失了。


关于这样的不确定(或?坏?)指针,我已阅读以下内容:

This code works fine, its output is : "Exception : Could not execute f9".

Nevertheless, in the catch clause, the pointer c is indeterminate, the pointee may have been lost.

About such indeterminate (or ?bad?) pointers, I have read the following :


如果运气不好,取消引用操作将立即崩溃或停止(Java表现为这个

方式)。如果你运气不好,那么糟糕的指针取消引用会破坏内存的随机区域,稍微改变一下程序的操作,以便以后无限期地出现一些错误。
http://cslibrary.stanford.edu/102/PointersAndMemory。 pdf



看来我运气不好,因为我的程序没有立即崩溃。

但我的问题是:它可以在以后因为崩溃而崩溃这个非法的解引用?


在这种情况下,我不会在未确定指针指向的内存区域写入。

我只读它。 />

所以,在这种情况下,内存是否真的会被损坏以致我的程序可能会在以后崩溃?


非常感谢你的输出

It seems I am unlucky, since my program has not crashed immediately.
But my question is : can it crash later because of this illicit dereferencing ?

In this case, I do not write in the area of memory pointed by by undeterminate pointer.
I only read it.

So, in such a case, can really the memory be corrupted so that my program may crash later ?

Thanks a lot for your ouputs

推荐答案

它不会丢失,因为它是一个常量字符串;它不会被f9范围破坏。

是的,读取不属于你的程序的内存将导致程序终止。
It is not lost as it''s a constant string; It is not destroyed with f9 scope.
And yes, reading memory that doesn''t belong to your program will cause program termination.


感谢您的回复,newb16,但在我的程序的catch子句中,我们不再处于f9范围内,所以,它应该丢失,不是吗?
thanks for your response, newb16, but in the catch clause of my program, we are no longer in f9 scope, so, there, it should be lost, isn''t it ?


严格来说读取不确定指针位置是未定义的行为。这意味着任何事情都可能发生,包括程序按预期运行,恶魔飞出你的鼻子。实际发生的事情可能会因系统上看起来完全不相关的事件而改变。


应该不惜一切代价避免未定义的行为。


作为newb16指出,虽然你要返回一个不确定的指针,但它是一个指向常量字符串的指针。您应该做的是抛出并捕获const char *以反映字符串的常量。
Strictly speaking reading an indeterminate pointer location is undefined behaviour. That means anything can happen including the program running as expected and demons flying out of your nose. What actually happens may change for what appears to be a completely unrelated event on the system.

Undefined behaviour should be avoided at all costs.

as newb16 pointed out though you you are returning an indeterminate pointer, it is a pointer to a constant string. What you should be doing is throwing and catching const char * to reflect the constness of the string.


这篇关于读取(不写入)坏指针会导致程序崩溃吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆