简体   繁体   中英

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

I have a super weird problem with glibc on Ubuntu.

Sample program 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 .

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). 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). 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).

This line allocates a single int and initializes it to the value 8 :

int *dd3 = new int(8);

If you want an array of 8 ints do this instead:

int *dd3 = new int[8];

Don't forget to correctly return the memory when you are done:

delete [] dd3;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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