Pergunta

I am trying to have some kind of dynamically growing array/data structure in C. Below is the C code I have for it. But after it prints the array, it gives a run-time error as shown below in the snapshot. What is going wrong? It is being compiled using MS-Visual C++ 2010 (Free version) on a Windows-7.

enter image description here

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

int main(void) {
 int *a;
 int i = 5;

 if((a = (int *)malloc(i * sizeof(int))) == NULL) {
  fprintf(stderr, "Error: failed malloc\n");
  return 1;
 }
 for(i = 0; i < 5; i++) 
  a[i] = i;

 printf("-- array after malloc\n");
 for(i = 0; i < 5; i++) 
  printf(" a[%d] = %d\n", i, a[i]);

 if((a = (int *)realloc(a, i * sizeof(int))) == NULL) {
  fprintf(stderr, "Error: failed realloc\n");
  return 1;
 }
 for(i = 0; i < 10; i++) 
  a[i] = i;


 printf("\n-- array after realloc\n");
 for(i = 0; i < 10; i++) 
  printf(" a[%d] = %d\n", i, a[i]);


 free(a);
 return 0;
}
Foi útil?

Solução

//<important> 
//weren't you supposed to do i = 10 here ????
//</important>
if((a = (int *)realloc(a, i * sizeof(int))) == NULL) {
  fprintf(stderr, "Error: failed realloc\n");
  return 1;
 }
 for(i = 0; i < 10; i++) 
  a[i] = i;

I think this was supposed to resize array to 10 and use it, but you never changed i to 10 so i is still 5 and you go out of range

Outras dicas

On this line:

if((a = (int *)realloc(a, i * sizeof(int))) == NULL) {

i still contains the value 5. So basically you are realloc'ing for 5 integers while you assign 10 integers in the next loop: an error.

This would be the fixed code:

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

int main(void) {
 int *a;
 int i;

 if((a = (int *)malloc(5 * sizeof(int))) == NULL) {
  fprintf(stderr, "Error: failed malloc\n");
  return 1;
 }

 for(i = 0; i < 5; i++) 
  a[i] = i;

 printf("-- array after malloc\n");
 for(i = 0; i < 5; i++) 
  printf(" a[%d] = %d\n", i, a[i]);

 if((a = (int *)realloc(a, 10 * sizeof(int))) == NULL) {
  fprintf(stderr, "Error: failed realloc\n");
  return 1;
 }

 for(i = 0; i < 10; i++) 
  a[i] = i;

 printf("\n-- array after realloc\n");
 for(i = 0; i < 10; i++) 
  printf(" a[%d] = %d\n", i, a[i]);


 free(a);
 return 0;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top