简体   繁体   English

当将字符串和int指针一起用作函数参数时,C ++程序崩溃

[英]C++ Program crashes when string and int pointer are used together as function arguments

I have a super weird problem with glibc on Ubuntu. 我在Ubuntu上使用glibc有一个非常奇怪的问题。

Sample program test.cpp: 示例程序test.cpp:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

bool abc(string unitstr,int *data)
{        

}

int main(int argc,char *argv[])
{

  int *dd3 = new int(8); 
  dd3[0]=1;dd3[1]=2;dd3[2]=3;dd3[3]=4;
  dd3[4]=5;dd3[5]=6;dd3[6]=7;dd3[7]=8;
  abc("sss",dd3);

  return 1;
}

Compile and run: 编译并运行:

g++ test.cpp
a.out

Result: 结果:

a.out: malloc.c:2451: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
Abort (core dumped)

With this line: 用这行:

int *dd3 = new int(8);

You're allocating and initializing a scalar , not an array: a single int , initialized with the value 8 . 你分配和初始化一个标量 ,而不是一个数组:一个int ,用初始化8

You need: 你需要:

int *dd3 = new int[8];
int *dd3 = new int(8);

This statement only allocates space for a single integer (and then initializes it with the number 8). 该语句仅为单个整数分配空间(然后将其初始化为数字8)。 You then proceed in using this pointer like a larger array, leading to undefined behavior that may (and indeed, seems to) manifest itself later on. 然后,您可以像使用更大的数组一样继续使用此指针,从而导致未定义的行为,稍后(可能确实)会表现出来。

Using new here seems unnecessary (and exception-unsafe, if nothing else). 在这里使用new似乎是不必要的(并且异常安全,如果没有其他原因)。 Just use a vector and be done with it (should you want to be able to resize the block inside the function, just pass the vector instead of a pointer). 只需使用vector并完成操作即可(如果您希望能够在函数内部调整块的大小,只需传递向量而不是指针即可)。

This line allocates a single int and initializes it to the value 8 : 这条线分配一个 int和其初始化为值8

int *dd3 = new int(8);

If you want an array of 8 ints do this instead: 如果要由8个ints的数组,请执行以下操作:

int *dd3 = new int[8];

Don't forget to correctly return the memory when you are done: 完成后,请不要忘记正确返回内存:

delete [] dd3;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM