本文介绍了为什么同时使用堆分配的内存我的程序抛出一个分割的错吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个程序来扭转一个字符串后,我无法理解为什么我得到了赛格故障而试图扭转字符串。我在下面列出我的程序。

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;void反转(字符*);诠释主(){
  字符*海峡=释放calloc(1,'\\ 0');
  的strcpy(STRmystring0123456789);
  反转(STR);
  的printf(反向字符串是:%S \\ n,STR);
  返回0;
}void反转(字符*字符串){
  焦炭CH,*开始,*结束;
  INT C = 0;
  INT长度= strlen的(字符串);
  开始=字符串;
  结束=字符串;  而(C<长度-1){
    结束++;
    C ++;
  }
  C = 0;  而(℃下长度/ 2){
    CH = *结束;
    *结束= *启动;
    *开始= CH;
    启动++;
    结束 - ;
    C ++;
  }
}

第一个问题:

尽管我已经拨出只有1内存字节的字符指针
STR(释放calloc(1,'\\ 0')),和我复制一个18字节的字符串 mystring0123456789 进去,并没有抛出任何错误,程序没有任何段错误的罚款。

为什么我的程序没有抛出一个错误?理想情况下,应该抛出一些错误,因为它没有任何的内存空间来存储大串。可有人扔光这个?

该方案完美跑去给我输出反向字符串为:9876543210gnirtsym

第二个问题:

如果替换语句

 的strcpy(STRmystring0123456789);

 海峡=mystring0123456789 \\ 0;

程序给出分段错误即使我已经分配了足够的内存STR(的malloc(100))。

为什么程序扔段错误?


解决方案

Your code had a bug -- of course it's not going to do what you expect. Fix the bug and the mystery will go away.

Because when you finish this, str points to a constant. This throws away the previous value of str, a pointer to memory you allocated, and replaces it with a pointer to that constant.

You cannot modify a constant, that's what makes it a constant. The strcpy function copies the constant into a variable which you can then modify.

Imagine if you could do this:

int* h = &2;

Now, if you did *h = 1; you'd be trying to change that constant 2 in your code, which of course you can't do.

That's effectively what you're doing with str="mystring0123456789\0";. It makes str point to that constant in your source code which, of course, you can't modify.

这篇关于为什么同时使用堆分配的内存我的程序抛出一个分割的错吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:36
查看更多