Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: mergesort code segfaulting on smallish arrays Date: Thu, 07 Nov 2019 10:34:21 -0800 Organization: None to speak of Lines: 43 Message-ID: References: <0ee77699-6964-4782-928b-5e5cdfc714db@googlegroups.com> <1JXwF.50019$kt1.13739@fx46.iad> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader02.eternal-september.org; posting-host="fdd2727d9421cbcb7e0942d3891e7ce6"; logging-data="14471"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/rhuk+YlQ+17qPhdf2rxu8" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:OxSwYlIXcQiVfCj8j/Lsxh9WT5U= sha1:cSETMViq0YBC7KAxQFtwObJAit8= Xref: csiph.com comp.lang.c:147736 DFS writes: > On 11/7/2019 10:48 AM, Malcolm McLean wrote: >> On Thursday, 7 November 2019 15:40:25 UTC, DFS wrote: >>> This code mergesorts an array of ints. Works fine for small arrays, but >>> craps out (Segmentation fault (core dumped)) at sizes > 500000. >>> >>> Ideas? >>> >>> void merge(int *arr, int left, int middle, int right) { >>> int i=0, j=0, k=0; >>> int leftLen = middle - left + 1; >>> int rightLen = right - middle; >>> int leftarr[leftLen]; >>> int rightarr[rightLen]; >>> >>> >> These are variable length arrays. They go on the stack. Stacks are usually >> small in relation to the total memory, they are designed to hold a few >> working variables, not entire datasets. You're probably exceeding stack >> capacity. > > replaced > int leftarr[leftLen]; > int rightarr[rightLen]; > > with > int *leftarr = malloc(sizeof(int) * (leftLen)); > int *rightarr = malloc(sizeof(int) * (rightLen)); Good, but a style point: int *leftarr = malloc(leftLen * sizeof *leftarr); int *rightarr = malloc(rightLen * sizeof *rightarr); By using sizeof *leftarr, you don't have to update the type if you decide later you want an array of double, for example. (The operand of sizeof is not evaluated in this case, so it doesn't matter that leftarr is uninitialized.) -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for Philips Healthcare void Void(void) { Void(); } /* The recursive call of the void */